JQuery Documentation - Bitbucket

Post on 09-Feb-2022

16 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

cdnbitbucketorg httpcdnbitbucketorggreydwarfjquerydocdownloadsjquery_refhtml

JQuery Documentation

Core

jQueryholdReady

Holds or releases the execut ion of jQuerys ready event

Added in version 16

jQueryholdReady(hold)undef ined

holdBoolean Indicates whether the ready hold is being requested or released

The $holdReady() method allows the caller to delay jQuerys ready event This advancedfeature would typically be used by dynamic script loaders that want to load addit ionalJavaScript such as jQuery plugins before allowing the ready event to occur even though theDOM may be ready This method must be called early in the document such as in the ltheadgtimmediately af ter the jQuery script tag Calling this method af ter the ready event has alreadyf ired will have no ef fect

To delay the ready event f irst call $holdReady(true) When the ready event should be releasedto execute call $holdReady(false) Note that mult iple holds can be put on the ready event onefor each $holdReady(true) call The ready event will not actually f ire unt il all holds have beenreleased with a corresponding $holdReady(false) and the normal document ready condit ionsare met (See ready for more informat ion)

Example 1 Delay the ready event unt il a custom plugin has loaded

Javascript

$holdReady(true)$getScript(mypluginjs function() $holdReady(false))

jQuerywhen

Provides a way to execute callback funct ions based on one or more objects usually Deferredobjects that represent asynchronous events

Added in version 15

jQuerywhen(deferreds)Promise

deferredsDeferred One or more Deferred objects or plain JavaScript objects

If a single Deferred is passed to jQuerywhen its Promise object (a subset of the Deferredmethods) is returned by the method Addit ional methods of the Promise object can be called toattach callbacks such as deferredthen When the Deferred is resolved or rejected usually bythe code that created the Deferred originally the appropriate callbacks will be called Forexample the jqXHR object returned by jQueryajax is a Deferred and can be used this way

$when( $ajax(testaspx) )then(function(ajaxArgs) alert(ajaxArgs[1]) ajaxArgs is [ success statusText jqXHR ] )

If a single argument is passed to jQuerywhen and it is not a Deferred it will be t reated as aresolved Deferred and any doneCallbacks at tached will be executed immediately ThedoneCallbacks are passed the original argument In this case any failCallbacks you might set arenever called since the Deferred is never rejected For example

$when( testing 123 )done( function(x) alert(xtesting) alerts 123 )

In the case where mult iple Deferred objects are passed to jQuerywhen the method returns thePromise from a new master Deferred object that t racks the aggregate state of all theDeferreds it has been passed The method will resolve its master Deferred as soon as all theDeferreds resolve or reject the master Deferred as soon as one of the Deferreds is rejected Ifthe master Deferred is resolved it is passed the resolved values of all the Deferreds that werepassed to jQuerywhen For example when the Deferreds are jQueryajax() requests thearguments will be the jqXHR objects for the requests in the order they were given in theargument list

In the mult iple-Deferreds case where one of the Deferreds is rejected jQuerywhen immediatelyf ires the failCallbacks for its master Deferred Note that some of the Deferreds may st ill beunresolved at that point If you need to perform addit ional processing for this case such ascanceling any unf inished ajax requests you can keep references to the underlying jqXHRobjects in a closure and inspectcancel them in the failCallback

Example 1 Execute a funct ion af ter two ajax requests are successful (See the jQueryajax()documentat ion for a complete descript ion of success and error cases for an ajax request)

Javascript

$when($ajax(page1php) $ajax(page2php))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 ] i f ( Whip Ittest(jqXHRresponseText) ) alert(First page has Whip It somewhere) )

Example 2 Execute the funct ion myFunc when both ajax requests are successful or myFailureif either one has an error

Javascript

$when($ajax(page1php) $ajax(page2php)) then(myFunc myFailure)

jQuerysub

Creates a new copy of jQuery whose propert ies and methods can be modif ied withoutaf fect ing the original jQuery object

Added in version 15

jQuerysub()jQuery

There are two specif ic use cases for which jQuerysub() was created The f irst was for providinga painless way of overriding jQuery methods without completely destroying the originalmethods and another was for helping to do encapsulat ion and basic namespacing for jQueryplugins

Note that jQuerysub() doesnt at tempt to do any sort of isolat ion - that s not its intent ion Allthe methods on the subd version of jQuery will st ill point to the original jQuery (events boundand triggered will st ill be through the main jQuery data will be bound to elements through themain jQuery Ajax queries and events will run through the main jQuery etc)

Note that if youre looking to use this for plugin development you should f irst strongly considerusing something like the jQuery UI widget factory which manages both state and plugin sub-methods Some examples of using the jQuery UI widget factory to build a plugin

The part icular use cases of this method can be best described through some examples

Example 1 Adding a method to a jQuery sub so that it isnt exposed externally

Javascript

(function() var sub$ = jQuerysub()

sub$fnmyCustomMethod = function() return just for me

sub$(document)ready(function() sub$(body)myCustomMethod() just for me ) )() typeof jQuery(body)myCustomMethod undefined

Example 2 Override some jQuery methods to provide new funct ionality

Javascript

(function() var myjQuery = jQuerysub()

myjQueryfnremove = function() New functionality Trigger a remove event thistrigger(remove)

Be sure to call the original jQuery remove method return jQueryfnremoveapply( this arguments )

myjQuery(function($) $(menu)cl ick(function() $(this)find(submenu)remove() )

A new remove event is now triggered from this copy of jQuery $(document)bind(remove function(e) $(etarget)parent()hide() ) ))()

Regular jQuery doesnt trigger a remove event when removing an element This functionality is only contained within the modified myjQuery

Example 3 Create a plugin that returns plugin-specif ic methods

Javascript

(function() Create a new copy of jQuery using sub() var plugin = jQuerysub()

Extend that copy with the new plugin methods pluginfnextend( open function() return thisshow() close function() return thishide() )

Add our plugin to the original jQuery jQueryfnmyplugin = function() thisaddClass(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 Call ing just $(main)open() wont work as open doesnt exist)

jQuerynoConflict

Relinquish jQuerys control of the $ variable

Added in version 10

jQuerynoConf lict (removeAll)Object

removeAllBoolean (opt ional) A Boolean indicat ing whether to remove all jQueryvariables f rom the global scope (including jQuery itself )

Many JavaScript libraries use $ as a funct ion or variable name just as jQuery does In jQueryscase $ is just an alias for jQuery so all funct ionality is available without using $ If we need touse another JavaScript library alongside jQuery we can return control of $ back to the otherlibrary with a call to $noConf lict ()

ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() Code that uses other l ibrarys $ can follow hereltscriptgt

This technique is especially ef fect ive in conjunct ion with the ready() methods ability to aliasthe jQuery object as within callback passed to ready() we can use $ if we wish without fear ofconf licts later

ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() jQuery(document)ready(function($) Code that uses jQuerys $ can follow here ) Code that uses other l ibrarys $ can follow hereltscriptgt

If necessary we can free up the jQuery name as well by passing true as an argument to themethod This is rarely necessary and if we must do this (for example if we need to use mult ipleversions of the jQuery library on the same page) we need to consider that most plug-ins relyon the presence of the jQuery variable and may not operate correct ly in this situat ion

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

Javascript

jQuerynoConfl ict() Do something with jQueryjQuery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

Example 2 Reverts the $ alias and then creates and executes a funct ion to provide the $ as ajQuery alias inside the funct ions scope Inside the funct ion the original $ object is not availableThis works well for most plugins that dont rely on any other library

Javascript

jQuerynoConfl ict()(function($) $(function() more code using $ as alias to jQuery ))(jQuery) other code using $ as an alias to the other l ibrary

Example 3 You can chain the jQuerynoConf lict () with the shorthand ready for a compact code

Javascript

jQuerynoConfl ict()(function() code using jQuery) other code using $ as an alias to the other l ibrary

Example 4 Creates a dif ferent alias instead of jQuery to use in the rest of the script

Javascript

var j = jQuerynoConfl ict() Do something with jQueryj(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

Example 5 Completely move jQuery to a new namespace in another object

Javascript

var dom = domquery = jQuerynoConfl ict(true)

Results

Do something with the new jQuerydomquery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none Do something with another version of jQueryjQuery(div gt p)hide()

jQuery

Accepts a string containing a CSS selector which is then used to match a set of elements

Added in version 14

jQuery()jQuery

In the f irst formulat ion listed above jQuery() acirceurordquo which can also be writ ten as $() acirceurordquo searchesthrough the DOM for any elements that match the provided selector and creates a new jQueryobject that references these elements

$(divfoo)

Selector Context

By default selectors perform their searches within the DOM start ing at the document rootHowever an alternate context can be given for the search by using the opt ional secondparameter to the $() funct ion For example to do a search within an event handler the searchcan be restricted like so

$(divfoo)cl ick(function() $(span this)addClass(bar))

When the search for the span selector is restricted to the context of this only spans within theclicked element will get the addit ional class

Internally selector context is implemented with the f ind() method so $(span this) is equivalentto $(this)f ind(span)

Using DOM elements

The second and third formulat ions of this funct ion create a jQuery object using one or moreDOM elements that were already selected in some other way A common use of this facility isto call jQuery methods on an element that has been passed to a callback funct ion through thekeyword this

$(divfoo)cl ick(function() $(this)sl ideUp())

This example causes elements to be hidden with a sliding animat ion when clicked Because thehandler receives the clicked item in the this keyword as a bare DOM element the element mustbe passed to the $() funct ion before applying jQuery methods to it

XML data returned from an Ajax call can be passed to the $() funct ion so individual elements of

the XML structure can be retrieved using f ind() and other DOM traversal methods

$post(urlxml function(data) var $child = $(data)find(child))

Cloning jQuery Objects

When a jQuery object is passed to the $() funct ion a clone of the object is created This newjQuery object references the same DOM elements as the init ial one

Returning an Empty Set

As of jQuery 14 calling the jQuery() method with no arguments returns an empty jQuery set(with a length property of 0) In previous versions of jQuery this would return a set containingthe document node

Example 1 Find all p elements that are children of a div element and apply a border to them

Javascript

$(div gt p)css(border 1px solid gray)

HTML

ltpgtoneltpgt ltdivgtltpgttwoltpgtltdivgt ltpgtthreeltpgt

Example 2 Find all inputs of type radio within the f irst form in the document

Javascript

$(inputradio documentforms[0])

Example 3 Find all div elements within an XML document f rom an Ajax response

Javascript

$(div xmlresponseXML)

Example 4 Set the background color of the page to black

Javascript

$(documentbody)css( background black )

Example 5 Hide all the input elements within a form

Javascript

$(myFormelements)hide()

jQuery

Creates DOM elements on the f ly f rom the provided string of raw HTML

Added in version 14

jQuery(html props)jQuery

htmlString A string def ining a single standalone HTML element (eg ltdivgt orltdivgtltdivgt)

propsObject An map of at t ributes events and methods to call on the newly-createdelement

Creating New Elements

If a string is passed as the parameter to $() jQuery examines the string to see if it looks likeHTML (ie it has lttag gt somewhere within the string) If not the string is interpreted as aselector expression as explained above But if the string appears to be an HTML snippetjQuery at tempts to create new DOM elements as described by the HTML Then a jQuery objectis created and returned that refers to these elements You can perform any of the usual jQuerymethods on this object

$(ltp id=testgtMy ltemgtnewltemgt textltpgt)appendTo(body)

If the HTML is more complex than a single tag without at t ributes as it is in the above examplethe actual creat ion of the elements is handled by the browsers innerHTML mechanism In mostcases jQuery creates a new

element and sets the innerHTML property of the element to the HTML snippet that was passedin When the parameter has a single tag such as$(ltimgAcirc gt) or $(ltagtltagt) jQuery creates the element using the nat ive JavaScriptcreateElement() funct ion

When passing in complex HTML some browsers may not generate a DOM that exact ly

replicates the HTML source provided As ment ioned we use the browsers innerHTML propertyto parse the passed HTML and insert it into the current document During this process somebrowsers f ilter out certain elements such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements inserted may not be representat ive of the original string passed

Filtering isnt however just limited to these tags For example Internet Explorer prior to version 8will also convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

To ensure cross-plat form compat ibility the snippet must be well-formed Tags that can containother elements should be paired with a closing tag

$(lta href=httpjquerycomgtltagt)

Alternat ively jQuery allows XML-like tag syntax (with or without a space before the slash)

$(ltagt)

Tags that cannot contain elements may be quick-closed or not

$(ltimg gt)$(ltinputgt)

When passing HTML to jQuery() please also note that text nodes are not t reated as DOMelements With the except ion of a few methods (such as content()) they are generallyotherwise ignored or removed Eg

var el = $(1ltbrgt2ltbrgt3) returns [ltbrgt 2 ltbrgt] el = $(1ltbrgt2ltbrgt3 gt) returns [ltbrgt 2 ltbrgt 3 ampgt]

This behaviour is expected

As of jQuery 14 the second argument to jQuery() can accept a map consist ing of a supersetof the propert ies that can be passed to the at t r() method Furthermore any event type can bepassed in and the following jQuery methods can be called val css html text data widthheight or of fset The name class must be quoted in the map since it is a JavaScript reservedword and className cannot be used since it is not the correct at t ribute name

Note Internet Explorer will not allow you to create an input or button element and change itstype you must specify the type using ltinput type=checkbox gt for example A demonstrat ionof this can be seen below

Unsupported in IE

$(ltinput gt type text name test)appendTo(body)

Supported workaround

$(ltinput type=text gt)attr( name test)appendTo(body)

Example 1 Create a div element (and all of its contents) dynamically and append it to the bodyelement Internally an element is created and its innerHTML property set to the given markup

Javascript

$(ltdivgtltpgtHelloltpgtltdivgt)appendTo(body)

Example 2 Create some DOM elements

Javascript

$(ltdivgt class test text Click me cl ick function() $(this)toggleClass(test) )appendTo(body)

jQuery

Binds a funct ion to be executed when the DOM has f inished loading

Added in version 10

jQuery(callback)jQuery

callbackFunct ion The funct ion to execute when the DOM is ready

This funct ion behaves just like $(document)ready() in that it should be used to wrap other $()operat ions on your page that depend on the DOM being ready While this funct ion is

technically chainable there really isnt much use for chaining against it

Example 1 Execute the funct ion when the DOM is ready to be used

Javascript

$(function() Document is ready )

Example 2 Use both the shortcut for $(document)ready() and the argument to write failsafejQuery code using the $ alias without relying on the global alias

Javascript

jQuery(function($) Your code using failsafe $ alias here )

Selectors

focus $(focus)

Selects element if it is current ly focused

Added in version 16

$(focus)

As with other pseudo-class selectors (those that begin with a ) it is recommended toprecede focus with a tag name or some other selector otherwise the universal selector () isimplied In other words the bare $(focus) is equivalent to $(focus) If you are looking for thecurrent ly focused element $( documentact iveElement ) will retrieve it without having to searchthe whole DOM tree

Example 1 Adds the focused class to whatever element has focus

Javascript

$()l ive(focus blur function(e) var el = $(this) setTimeout(function() eltoggleClass(focused elis(focus)) 0))

CSS

focused background abcdef

HTML

ltinput tabIndex=1gtltinput tabIndex=2gtltselect tabIndex=3gt ltoptiongtselect menultoptiongtltselectgtltdiv tabIndex=4gt a divltdivgt

selected $(selected)

Selects all elements that are selected

Added in version 10

$(selected)

The selected selector works for ltopt iongt elements It does not work for checkboxes or radioinputs use checked for them

Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

Javascript

$(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) trigger(change)

CSS

div colorred

HTML

ltselect name=garden multiple=multiplegt

ltoptiongtFlowersltoptiongt ltoption selected=selectedgtShrubsltoptiongt ltoptiongtTreesltoptiongt ltoption selected=selectedgtBushesltoptiongt

ltoptiongtGrassltoptiongt ltoptiongtDirtltoptiongt ltselectgt ltdivgtltdivgt

checked $(checked)

Matches all elements that are checked

Added in version 10

$(checked)

The checked selector works for checkboxes and radio buttons For select elements use theselected selector

Example 1 Finds all input elements that are checked

Javascript

function countChecked() var n = $(inputchecked)length $(div)text(n + (n lt= 1 is are) + checked)countChecked()$(checkbox)cl ick(countChecked)

CSS

div colorred

HTML

ltformgt ltpgt ltinput type=checkbox name=newsletter checked=checked value=Hourly gt

ltinput type=checkbox name=newsletter value=Daily gt ltinput type=checkbox name=newsletter value=Weekly gt

ltinput type=checkbox name=newsletter checked=checked value=Monthly gt ltinput type=checkbox name=newsletter value=Yearly gt ltpgtltformgtltdivgtltdivgt

Example 2

Javascript

$(input)cl ick(function() $(log)html( $(checked)val() + is checked ))

CSS

input label l ine-height 15em

HTML

ltformgt ltdivgt ltinput type=radio name=fruit value=orange id=orangegt ltlabel for=orangegtorangeltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=apple id=applegt ltlabel for=applegtappleltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=banana id=bananagt ltlabel for=bananagtbananaltlabelgt ltdivgt ltdiv id=loggtltdivgtltformgt

disabled $(disabled)

Selects all elements that are disabled

Added in version 10

$(disabled)

As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(disabled) is equivalent to $(disabled) so $(inputdisabled) should beused instead

Example 1 Finds all input elements that are disabled

Javascript

$(inputdisabled)val(this is it)

HTML

ltformgt

ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

enabled $(enabled)

Selects all elements that are enabled

Added in version 10

$(enabled)

As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(enabled) is equivalent to $(enabled) so $(inputenabled) should beused instead

Example 1 Finds all input elements that are enabled

Javascript

$(inputenabled)val(this is it)

HTML

ltformgt

ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

file $(file)

Selects all elements of type f ile

Added in version 10

$(f ile)

f ile is equivalent to [type=f ile] 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 theuniversal selector () is implied In other words the bare $(f ile) is equivalent to $(f ile) so$(inputf ile) should be used instead

Example 1 Finds all f ile inputs

Javascript

var input = $(inputfi le)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height45px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

button $(button)

Selects all but ton elements and elements of type button

Added in version 10

$(button)

Example 1 Finds all but ton inputs

Javascript

var input = $(button)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height45px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

reset $(reset)

Selects all elements of type reset

Added in version 10

$(reset)

reset is equivalent to [type=reset]

Example 1 Finds all reset inputs

Javascript

var input = $(inputreset)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height45px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

image $(image)

Selects all elements of type image

Added in version 10

$(image)

image is equivalent to [type=image]

Example 1 Finds all image inputs

Javascript

var input = $(inputimage)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height45px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

submit $(submit)

Selects all elements of type submit

Added in version 10

$(submit)

The submit selector typically applies to button or input elements Note that some browserstreat ltbuttongt element as type=default implicit ly while others (such as Internet Explorer) donot

Example 1 Finds all submit elements that are descendants of a td element

Javascript

var submitEl = $(td submit) parent(td) css(backgroundyellow border3px red solid) end() $(result)text( jQuery matched + submitEllength + elements)

so it wont 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 = inputElattr(type) type= + inputElattr(type) + $(el)before(lttdgt + inputEl[0]nodeName + inputType + lttdgt) )

CSS

textarea height45px

HTML

lttablegtltformgtlttable id=exampleTable border=1 cellpadding=10 align=centergt

lttrgt ltthgt Element Type ltthgt ltthgt Element ltthgt

lttr lttrgt lttdgt ltinput type=button value=Input Buttongt lttdgt

lttrgt lttrgt lttdgt ltinput type=checkbox gt lttdgt

lttrgt lttrgt lttdgt ltinput type=fi le gt lttdgt

lttrgt lttrgt lttdgt ltinput type=hidden gt lttdgt

lttrgt lttrgt lttdgt ltinput type=image gt lttdgt

lttrgt lttrgt lttdgt ltinput type=password gt lttdgt

lttrgt lttrgt lttdgt ltinput type=radio gt lttdgt

lttrgt lttrgt lttdgt ltinput type=reset gt lttdgt

lttrgt lttrgt lttdgt ltinput type=submit gt lttdgt

lttrgt lttrgt lttdgt ltinput type=text gt lttdgt

lttrgt lttrgt lttdgt ltselectgtltoptiongtOptionltoptiongtltselectgt lttdgt

lttrgt lttrgt lttdgt lttextareagtlttextareagt lttdgt lttrgt

lttrgt lttdgt ltbuttongtButtonltbuttongt lttdgt lttrgt lttrgt lttdgt ltbutton type=submitgtButton type=submitltbuttongt lttdgt lttrgt

lttablegtltformgtltdiv id=resultgtltdivgt

checkbox $(checkbox)

Selects all elements of type checkbox

Added in version 10

$(checkbox)

$(checkbox) is equivalent to $([type=checkbox]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(checkbox) isequivalent to $(checkbox) so $(inputcheckbox) should be used instead

Example 1 Finds all checkbox inputs

Javascript

var input = $(form inputcheckbox)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height25px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=checkbox gt ltinput type=fi le gt ltinput type=hidden gt

ltinput type=image gt ltinput type=password gt ltinput type=radio gt

ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

ltdivgt ltdivgt

radio $(radio)

Selects all elements of type radio

Added in version 10

$(radio)

$(radio) is equivalent to $([type=radio]) As with other pseudo-class selectors (those thatbegin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(radio) is equivalentto $(radio) so $(inputradio) should be used instead

To select a set of associated radio buttons you might use $(input[name=gender]radio)

Example 1 Finds all radio inputs

Javascript

var input = $(form inputradio)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height25px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio name=asdf gt ltinput type=radio name=asdf gt

ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

ltdivgt ltdivgt

password $(password)

Selects all elements of type password

Added in version 10

$(password)

$(password) is equivalent to $([type=password]) As with other pseudo-class selectors (thosethat 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 $(password) isequivalent to $(password) so $(inputpassword) should be used instead

Example 1 Finds all password inputs

Javascript

var input = $(inputpassword)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height45px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

text $(text)

Selects all elements of type text

Added in version 10

$(text)

$(text ) is equivalent to $([type=text ]) and thus selects all ltinput type=textgt elements Aswith other pseudo-class selectors (those that begin with a ) it is recommended to precede itwith a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(text ) is equivalent to $(text ) so $(inputtext ) should be usedinstead

Note As of jQuery 152 text selects input elements that have no specif ied type at t ribute (inwhich case type=text is implied)

Example 1 Finds all text inputs

Javascript

var input = $(form inputtext)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

CSS

textarea height25px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

input $(input)

Selects all input textarea select and button elements

Added in version 10

$(input)

The input selector basically selects all form controls

Example 1 Finds all input elements

Javascript

var all Inputs = $(input) var formChildren = $(form gt ) $(messages)text(Found + all Inputslength + inputs and the form has + formChildrenlength + children) so it wont submit $(form)submit(function () return false )

CSS

textarea height25px

HTML

ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdiv id=messagesgt ltdivgt

only-child $(only-child)

Selects all elements that are the only child of their parent

Added in version 114

$(only-child)

If the parent has other child elements nothing is matched

Example 1 Change the text and add a border for each button that is the only child of its parent

Javascript

$(div buttononly-child)text(Alone)css(border 2px blue solid)

CSS

div width100px height80px margin5px floatleft backgroundb9e

HTML

ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongtltdivgt

ltdivgt ltbuttongtSiblingltbuttongtltdivgtltdivgt Noneltdivgt

ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt

ltdivgtltdivgt ltbuttongtSiblingltbuttongtltdivgt

last-child $(last-child)

Selects all elements that are the last child of their parent

Added in version 114

$(last-child)

While last matches only a single element last-child can match more than one one for eachparent

Example 1 Finds the last span in each matched div and adds some css plus a hover state

Javascript

$(div spanlast-child) css(colorred fontSize80) hover(function () $(this)addClass(solast) function () $(this)removeClass(solast) )

CSS

spansolast text-decorationl ine-through

HTML

ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

ltspangtSamltspangt ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt

ltspangtRalphltspangt ltspangtDavidltspangt ltdivgt

first-child $(first-child)

Selects all elements that are the f irst child of their parent

Added in version 114

$(f irst-child)

While f irst matches only a single element the f irst-child selector can match more than oneone for each parent This is equivalent to nth-child(1)

Example 1 Finds the f irst span in each matched div to underline and add a hover state

Javascript

$(div spanfirst-child) css(text-decoration underline) hover(function () $(this)addClass(sogreen) function () $(this)removeClass(sogreen) )

CSS

span color008 spansogreen colorgreen font-weight bolder

HTML

ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt ltspangtRalphltspangt

ltdivgt

nth-child $(nth-child(indexevenoddequation))

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

Added in version 114

$(nth-child(indexevenoddequat ion))

indexNumberString The index of each child to match start ing with 1 the string evenor odd or an equat ion ( eg nth-child(even) nth-child(4n) )

Because jQuerys implementat ion of nth-child(n) is strict ly derived from the CSS specif icat ionthe value of n is 1-indexed meaning that the count ing starts at 1 For all other selectorexpressions however jQuery follows JavaScript s 0-indexed count ing Therefore given asingle ltulgt containing two ltligts $(linth-child(1)) selects the f irst ltligt while $(lieq(1)) selectsthe second

The nth-child(n) pseudo-class is easily confused with eq(n) even though the two can result indramat ically dif ferent matched elements With nth-child(n) all children are counted regardlessof what they are and the specif ied element is selected only if it matches the selector at tachedto the pseudo-class With eq(n) only the selector at tached to the pseudo-class is counted notlimited 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 W3C CSS specif icat ion

Example 1 Finds the second li in each matched ul and notes it

Javascript

$(ul l i nth-child(2))append(ltspangt - 2ndltspangt)

CSS

div floatleft span colorblue

HTML

ltdivgtltulgt ltligtJohnltligt ltligtKarlltl igt ltligtBrandonltligt

ltulgtltdivgt ltdivgtltulgt ltligtSamltligt ltulgtltdivgt

ltdivgtltulgt ltligtGlenltligt ltligtTaneltligt ltligtRalphltligt

ltligtDavidltligt ltulgtltdivgt

Example 2 This is a playground to see how the selector works with dif ferent strings Not icethat this is dif ferent f rom the even and odd which have no regard for parent and just f ilter thelist of elements to every other one The nth-child however counts the index of the child to itspart icular parent In any case it s easier to see than explain so

Javascript

$(button)cl ick(function () var str = $(this)text() $(tr)css(background white) $(tr + str)css(background ff0000) $(inner)text(str) )

CSS

button displayblock font-size12px width100px div floatleft margin10px font-size10px border1px solid black span colorblue font-size18px inner colorred td width50px text-aligncenter

HTML

ltdivgt ltbuttongtnth-child(even)ltbuttongt ltbuttongtnth-child(odd)ltbuttongt ltbuttongtnth-child(3n)ltbuttongt

ltbuttongtnth-child(2)ltbuttongt ltdivgt ltdivgt ltbuttongtnth-child(3n+1)ltbuttongt ltbuttongtnth-child(3n+2)ltbuttongt

ltbuttongtevenltbuttongt ltbuttongtoddltbuttongt ltdivgt ltdivgtlttablegt

lttrgtlttdgtJohnlttdgtlttrgt lttrgtlttdgtKarllttdgtlttrgt lttrgtlttdgtBrandonlttdgtlttrgt

lttrgtlttdgtBenjaminlttdgtlttrgt lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtSamlttdgtlttrgt

lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtGlenlttdgtlttrgt lttrgtlttdgtTanelttdgtlttrgt

lttrgtlttdgtRalphlttdgtlttrgt lttrgtlttdgtDavidlttdgtlttrgt lttrgtlttdgtMikelttdgtlttrgt

lttrgtlttdgtDanlttdgtlttrgt lttablegtltdivgt ltspangt trltspan id=innergtltspangt

ltspangt

attributeContainsPrefix $([attribute|=value])

Selects elements that have the specif ied at t ribute with a value either equal to a given string orstart ing with that string followed by a hyphen (-)

Added in version 10

$([at t ribute|=value])

attributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

This selector was introduced into the CSS specif icat ion to handle language at t ributes

Example 1 Finds all links with an href lang at t ribute that is english

Javascript

$(a[hreflang|=en])css(border3px dotted green)

HTML

lta href=examplehtml hreflang=engtSome textltagt

lta href=examplehtml hreflang=en-UKgtSome other textltagt

lta href=examplehtml hreflang=englishgtwill not be outl inedltagt

CSS

a display inl ine-block

attributeContainsWord $([attribute~=value])

Selects elements that have the specif ied at t ribute with a value containing a given worddelimited by spaces

Added in version 10

$([at t ribute~=value])

at t ributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

This selector matches the test string against each word in the at t ribute value where a word isdef ined as a string delimited by whitespace The selector matches if the test string is exact lyequal to any of the words

Example 1 Finds all inputs with a name attribute that contains the word man and sets the

value with some text

Javascript

$( input[name~=man])val(mr man is in it)

HTML

ltinput name=man-news gt

ltinput name=milk man gt ltinput name=letterman2 gt ltinput name=newmilk gt

attributeMultiple$([attributeFilter1][attributeFilter2][attributeFilterN])

Matches elements that match all of the specif ied at t ribute f ilters

Added in version 10

$([at t ributeFilter1][at t ributeFilter2][at t ributeFilterN])

at t ributeFilter1Selector An at t ribute f ilter

at t ributeFilter2Selector Another at t ribute f ilter reducing the select ion even more

attributeFilterNSelector (opt ional) As many more at t ribute f ilters as necessary

Example 1 Finds all inputs that have an id at t ribute and whose name attribute ends with manand sets the value

Javascript

$( input[id][name$=man])val(only this one)

HTML

ltinput id=man-news name=man-news gt

ltinput name=milkman gt ltinput id=letterman name=new-letterman gt ltinput name=newmilk gt

attributeContains $([attribute=value])

Selects elements that have the specif ied at t ribute with a value containing the a given substring

Added in version 10

$([at t ribute=value])

at t ributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

This is the most generous of the jQuery at t ribute selectors that match against a value It willselect an element if the selectors string appears anywhere within the element s at t ribute valueCompare this selector with the Attribute Contains Word selector (eg [at t r~=word]) which ismore appropriate in many cases

Example 1 Finds all inputs with a name attribute that contains man and sets the value withsome text

Javascript

$( input[name=man])val(has man in it)

HTML

ltinput name=man-news gt

ltinput name=milkman gt ltinput name=letterman2 gt ltinput name=newmilk gt

attributeEndsWith $([attribute$=value])

Selects elements that have the specif ied at t ribute with a value ending exact ly with a givenstring The comparison is case sensit ive

Added in version 10

$([at t ribute$=value])

at t ributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

Example 1 Finds all inputs with an at t ribute name that ends with let ter and puts text in them

Javascript

$( input[name$=letter])val(a letter)

HTML

ltinput name=newsletter gt

ltinput name=milkman gt ltinput name=jobletter gt

attributeStartsWith $([attribute^=value])

Selects elements that have the specif ied at t ribute with a value beginning exact ly with a givenstring

Added in version 10

$([at t ribute^=value])

at t ributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

This selector can be useful for ident ifying elements in pages produced by server-sideframeworks that produce HTML with systemat ic element IDs However it will be slower thanusing a class selector so leverage classes if you can to group like elements

Example 1 Finds all inputs with an at t ribute name that starts with news and puts text in them

Javascript

$( input[name^=news])val(news here)

HTML

ltinput name=newsletter gt

ltinput name=milkman gt ltinput name=newsboy gt

attributeNotEqual $([attribute=value])

Select elements that either dont have the specif ied at t ribute or do have the specif ied at t ributebut not with a certain value

Added in version 10

$([at t ribute=value])

at t ributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

This selector is equivalent to not([at t r=value])

Example 1 Finds all inputs that dont have the name newslet ter and appends text to the spannext to it

Javascript

$( input[name=newsletter])next()append(ltbgt not newsletterltbgt)

HTML

ltdivgt

ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtname is newsletterltspangt

ltdivgt ltdivgt ltinput type=radio value=Cold Fusion gt ltspangtno nameltspangt

ltdivgt ltdivgt ltinput type=radio name=accept value=Evil Plans gt

ltspangtname is acceptltspangt ltdivgt

attributeEquals $([attribute=value])

Selects elements that have the specif ied at t ribute with a value exact ly equal to a certain value

Added in version 10

$([at t ribute=value])

attributeString An at t ribute name

valueString An at t ribute value Quotes are mandatory

Example 1 Finds all inputs with a value of Hot Fuzz and changes the text of the next siblingspan

Javascript

$( input[value=Hot Fuzz])next()text( Hot Fuzz)

HTML

ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtnameltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Cold Fusion gt ltspangtvalueltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Evil Plans gt ltspangtvalueltspangt ltlabelgt ltdivgt

attributeHas $([attribute])

Selects elements that have the specif ied at t ribute with any value

Added in version 10

$([at t ribute])

at t ributeString An at t ribute name

Example 1 Bind a single click that adds the div id to its text

Javascript

$(div[id])one(cl ick function() var idString = $(this)text() + = + $(this)attr( id) $(this)text(idString) )

HTML

ltdivgtno idltdivgt ltdiv id=heygtwith idltdivgt

ltdiv id=theregthas an idltdivgt ltdivgtnopeltdivgt

visible $(visible)

Selects all elements that are visible

Added in version 10

$(visible)

Elements can be considered hidden for several reasons

They have a CSS display value of none

They are form elements with type=hidden

Their width and height are explicit ly set to 0

An ancestor element is hidden so the element is not shown on the page

Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start at the animat ion

How visible is calculated was changed in jQuery 132 The release notes out line the changes inmore detail

Example 1 Make all visible divs turn yellow on click

Javascript

$(divvisible)cl ick(function () $(this)css(background yellow) ) $(button)cl ick(function () $(divhidden)show(fast) )

CSS

div width50px height40px margin5px border3px outset green floatleft starthidden displaynone

HTML

ltbuttongtShow hidden to see they dont changeltbuttongt ltdivgtltdivgt ltdiv class=starthiddengtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdiv style=displaynonegtltdivgt

hidden $(hidden)

Selects all elements that are hidden

Added in version 10

$(hidden)

Elements can be considered hidden for several reasons

They have a CSS display value of none

They are form elements with type=hidden

Their width and height are explicit ly set to 0

An ancestor element is hidden so the element is not shown on the page

Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start of the animat ion

How hidden is determined was changed in jQuery 132 An element is assumed to be hidden if itor any of its parents consumes no space in the document CSS visibility isnt taken into account(therefore $(elem)css(visibilityhidden)is(hidden) == false) The release notes out line thechanges in more detail

Example 1 Shows all hidden divs and counts hidden inputs

Javascript

in some browsers hidden includes head title script etcvar hiddenEls = $(body)find(hidden)not(script)

$(spanfirst)text(Found + hiddenElslength + hidden elements total)$(divhidden)show(3000)$(spanlast)text(Found + $(inputhidden)length + hidden inputs)

CSS

div width70px height40px backgroundee77ff margin5px floatleft span displayblock clearleft colorred starthidden displaynone

HTML

ltspangtltspangt ltdivgtltdivgt ltdiv style=displaynonegtHiderltdivgt ltdivgtltdivgt

ltdiv class=starthiddengtHiderltdivgt ltdivgtltdivgt ltformgt ltinput type=hidden gt

ltinput type=hidden gt ltinput type=hidden gt ltformgt ltspangt

ltspangt

parent $(parent)

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

Added in version 10

$(parent)

This is the inverse of empty

One important thing to note regarding the use of parent (and empty) is that child elementsinclude text nodes

The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elements

on the other hand are empty (ie have no children) by def init ion ltinputgt ltimggt ltbrgt and lthrgtfor example

Example 1 Finds all tds with children including text

Javascript

$(tdparent)fadeTo(1500 03)

CSS

td width40px backgroundgreen

HTML

lttable border=1gt

lttrgtlttdgtValue 1lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtValue 2lttdgtlttdgtlttdgtlttrgt

lttablegt

has $(has(selector))

Selects elements which contain at least one element that matches the specif ied selector

Added in version 114

$(has(selector))

selectorSelector Any selector

The expression $(divhas(p)) matches a ltdivgt if a ltpgt exists anywhere among its descendantsnot just as a direct child

Example 1 Adds the class test to all divs that have a paragraph inside of them

Javascript

$(divhas(p))addClass(test)

HTML

ltdivgtltpgtHello in a paragraphltpgtltdivgt

ltdivgtHello again (with no paragraph)ltdivgt

CSS

test border 3px inset red

empty $(empty)

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

Added in version 10

$(empty)

This is the inverse of parent

One important thing to note with empty (and parent) is that child elements include text nodes

The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elementson the other hand are empty (ie have no children) by def init ion and

for example

Example 1 Finds all elements that are empty - they dont have child elements or text

Javascript

$(tdempty)text(Was empty)css(background rgb(255220200))

CSS

td text-aligncenter

HTML

lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtTD 2lttdgtlttdgtlttdgtlttrgt

lttrgtlttdgtlttdgtlttdgtTD5lttdgtlttrgt lttablegt

contains $(contains(text))

Select all elements that contain the specif ied text

Added in version 114

$(contains(text))

text String A string of text to look for It s case sensit ive

The matching text can appear direct ly within the selected element in any of that element sdescendants or a combinat ion thereof As with at t ribute value selectors text inside theparentheses of contains() can be writ ten as bare words or surrounded by quotat ion marks Thetext must have matching case to be selected

Example 1 Finds all divs containing John and underlines them

Javascript

$(divcontains( John))css(text-decoration underline)

HTML

ltdivgtJohn Resigltdivgt

ltdivgtGeorge MartinltdivgtltdivgtMalcom John SinclairltdivgtltdivgtJ Ohnltdivgt

animated $(animated)

Select all elements that are in the progress of an animat ion at the t ime the selector is run

Added in version 12

$(animated)

Example 1 Change the color of any div that is animated

Javascript

$(run)cl ick(function() $(divanimated)toggleClass(colored) ) function animateIt() $(mover)sl ideToggle(slow animateIt) animateIt()

HTML

ltbutton id=rungtRunltbuttongt

ltdivgtltdivgt ltdiv id=movergtltdivgt ltdivgtltdivgt

CSS

div backgroundyellow border1px solid AAA width80px height80px margin0 5px floatleft divcolored backgroundgreen

header $(header)

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

Added in version 12

$(header)

Example 1 Adds a background and text color to all the headers on the page

Javascript

$(header)css( backgroundCCC colorblue )

HTML

lth1gtHeader 1lth1gt

ltpgtContents 1ltpgt lth2gtHeader 2lth2gt ltpgtContents 2ltpgt

CSS

body font-size 10px font-family Arial h1 h2 margin 3px 0

lt $(lt(index))

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

Added in version 10

$(lt (index))

indexNumber Zero-based index

index-related selectors

The index-related selectors (including this less than selector) f ilter the set of elements thathave matched the expressions that precede them They narrow the set down based on theorder of the elements within this matched set For example if elements are f irst selected with aclass selector (myclass) and four elements are returned these elements are given indices 0through 3 for the purposes of these selectors

Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasslt (1)) selects the f irst element in the document with the class myclass ratherthan select ing no elements In contrast nth-child(n) uses 1-based indexing to conform to theCSS specif icat ion

Example 1 Finds TDs less than the one with the 4th index (TD4)

Javascript

$(tdlt(4))css(color red)

HTML

lttable border=1gt

lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

gt $(gt(index))

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

Added in version 10

$(gt(index))

indexNumber Zero-based index

index-related selectors

The index-related selector expressions (including this greater than selector) f ilter the set ofelements that have matched the expressions that precede them They narrow the set downbased on the order of the elements within this matched set For example if elements are f irstselected with a class selector (myclass) and four elements are returned these elements aregiven indices 0 through 3 for the purposes of these selectors

Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclassgt(1)) selects elements af ter the second element in the document with theclass myclass rather than af ter the f irst In contrast nth-child(n) uses 1-based indexing toconform to the CSS specif icat ion

Example 1 Finds TD 5 and higher Reminder the indexing starts at 0

Javascript

$(tdgt(4))css(text-decoration l ine-through)

HTML

lttable border=1gt

lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgt lttablegt

eq $(eq(index))

Select the element at index n within the matched set

Added in version 10

$(eq(index))

indexNumber Zero-based index of the element to match

The index-related selectors (eq() lt () gt() even odd) f ilter the set of elements that havematched the expressions that precede them They narrow the set down based on the order ofthe elements within this matched set For example if elements are f irst selected with a classselector (myclass) and four elements are returned these elements are given indices 0 through3 for the purposes of these selectors

Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasseq(1)) selects the second element in the document with the class myclassrather than the f irst In contrast nth-child(n) uses 1-based indexing to conform to the CSSspecif icat ion

Unlike the eq(index) method the eq(index) selector does not accept a negat ive value for indexFor example while $(li)eq(-1) selects the last li element $(lieq(-1)) selects nothing

Example 1 Finds the third td

Javascript

$(tdeq(2))css(color red)

HTML

lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

Example 2 Apply three dif ferent styles to list items to demonstrate that eq() is designed toselect a single element while nth-child() or eq() within a looping construct such as each() canselect mult iple elements

Javascript

applies yellow background color to a single ltligt$(ulnav l i eq(1))css( backgroundColor ff0 )

applies ital ics to text of the second ltligt within each ltul class=navgt$(ulnav)each(function(index) $(this)find(l i eq(1))css( fontStyle ital ic ))

applies red text color to descendants of ltul class=navgt for each ltligt that is the second child of its parent$(ulnav l i nth-child(2))css( color red )

HTML

ltul class=navgt ltligtList 1 item 1ltligt ltligtList 1 item 2ltligt ltligtList 1 item 3ltligtltulgtltul class=navgt ltligtList 2 item 1ltligt ltligtList 2 item 2ltligt ltligtList 2 item 3ltligtltulgt

odd $(odd)

Selects odd elements zero-indexed See also even

Added in version 10

$(odd)

In part icular note that the 0-based indexing means that counter-intuit ively odd selects thesecond element fourth element and so on within the matched set

Example 1 Finds odd table rows matching the second fourth and so on (index 1 3 5 etc)

Javascript

$(trodd)css(background-color bbbbff)

CSS

table backgroundf3f7f5

HTML

lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

even $(even)

Selects even elements zero-indexed See also odd

Added in version 10

$(even)

In part icular note that the 0-based indexing means that counter-intuit ively even selects thef irst element third element and so on within the matched set

Example 1 Finds even table rows matching the f irst third and so on (index 0 2 4 etc)

Javascript

$(treven)css(background-color bbbbff)

CSS

table backgroundeeeeee

HTML

lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

not $(not(selector))

Selects all elements that do not match the given selector

Added in version 10

$(not(selector))

selectorSelector A selector with which to f ilter by

All selectors are accepted inside not() for example not(div a) and not(diva)

Additional Notes

The not() method will end up providing you with more readable select ions than pushingcomplex selectors or variables into a not() selector f ilter In most cases it is a better choice

Example 1 Finds all inputs that are not checked and highlights the next sibling span Not icethere is no change when clicking the checkboxes since no click events have been linked

Javascript

$(inputnot(checked) + span)css(background-color yellow) $(input)attr(disabled disabled)

HTML

ltdivgt ltinput type=checkbox name=a gt ltspangtMaryltspangtltdivgt

ltdivgt ltinput type=checkbox name=b gt ltspangtlcmltspangt

ltdivgtltdivgt ltinput type=checkbox name=c checked=checked gt

ltspangtPeterltspangtltdivgt

last $(last)

Selects the last matched element

Added in version 10

$(last)

Note that last selects a single element by f iltering the current jQuery collect ion and matchingthe last element within it

Example 1 Finds the last table row

Javascript

$(trlast)css(backgroundColor yellow fontWeight bolder)

HTML

lttablegt

lttrgtlttdgtFirst Rowlttdgtlttrgt lttrgtlttdgtMiddle Rowlttdgtlttrgt lttrgtlttdgtLast Rowlttdgtlttrgt

lttablegt

first $(first)

Selects the f irst matched element

Added in version 10

$(f irst)

The f irst pseudo-class is equivalent to eq(0) It could also be writ ten as lt (1) While thismatches only a single element f irst-child can match more than one One for each parent

Example 1 Finds the f irst table row

Javascript

$(trfirst)css(font-style ital ic)

CSS

td colorblue font-weightbold

HTML

lttablegt lttrgtlttdgtRow 1lttdgtlttrgt lttrgtlttdgtRow 2lttdgtlttrgt

lttrgtlttdgtRow 3lttdgtlttrgt lttablegt

next siblings $(prev ~ siblings)

Selects all sibling elements that follow af ter the prev element have the same parent andmatch the f iltering siblings selector

Added in version 10

$(prev ~ siblings)

prevSelector Any valid selector

siblingsSelector A selector to f ilter elements that are the following siblings of the f irstselector

The notable dif ference between (prev + next) and (prev ~ siblings) is their respect ive reachWhile the former reaches only to the immediately following sibling element the lat ter extendsthat reach to all following sibling elements

Example 1 Finds all divs that are siblings af ter the element with prev as its id Not ice the spanisnt selected since it is not a div and the niece isnt selected since it is a child of a sibling notan actual sibling

Javascript

$(prev ~ div)css(border 3px groove blue)

CSS

divspan displayblock width80px height80px margin5px backgroundbbffaa floatleft font-size14px divsmall width60px height25px font-size12px backgroundfab

HTML

ltdivgtdiv (doesnt match since before prev)ltdivgt ltspan id=prevgtspanprevltspangt ltdivgtdiv siblingltdivgt

ltdivgtdiv sibling ltdiv id=smallgtdiv nieceltdivgtltdivgt ltspangtspan sibling (not div)ltspangt ltdivgtdiv siblingltdivgt

next adjacent $(prev + next)

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

Added in version 10

$(prev + next)

prevSelector Any valid selector

nextSelector A selector to match the element that is next to the f irst selector

One important point to consider with both the next adjacent sibling selector (prev + next) andthe general sibling selector (prev ~ siblings) is that the elements on either side of thecombinator must share the same parent

Example 1 Finds all inputs that are next to a label

Javascript

$(label + input)css(color blue)val(Labeled)

HTML

ltformgt

ltlabelgtNameltlabelgt ltinput name=name gt ltfieldsetgt ltlabelgtNewsletterltlabelgt

ltinput name=newsletter gt ltfieldsetgt ltformgt ltinput name=none gt

child $(parent gt child)

Selects all direct child elements specif ied by child of elements specif ied by parent

Added in version 10

$(parent gt child)

parentSelector Any valid selector

childSelector A selector to f ilter the child elements

As a CSS selector the child combinator is supported by all modern web browsers includingSafari Firefox Opera Chrome and Internet Explorer 7 and above but notably not by InternetExplorer versions 6 and below However in jQuery this selector (along with all others) worksacross all supported browsers including IE6

The child combinator (E gt F) can be thought of as a more specif ic form of the descendantcombinator (E F) in that it selects only f irst-level descendants

Note The $(gt elem context) selector will be deprecated in a future release Itsusage is thus discouraged in lieu of using alternative selectors

Example 1 Places a border around all list items that are children of

Javascript

$(ultopnav gt l i)css(border 3px double red)

CSS

body font-size14px

HTML

ltul class=topnavgt ltligtItem 1ltligt ltligtItem 2 ltulgtltligtNested item 1ltligtltligtNested item 2ltligtltligtNested item 3ltligtltulgt ltl igt ltligtItem 3ltligtltulgt

descendant $(ancestor descendant)

Selects all elements that are descendants of a given ancestor

Added in version 10

$(ancestor descendant)

ancestorSelector Any valid selector

descendantSelector A selector to f ilter the descendant elements

A descendant of an element could be a child grandchild great-grandchild and so on of thatelement

Example 1 Finds all input descendants of forms

Javascript

$(form input)css(border 2px dotted blue)

CSS

body font-size14px form border2px green solid padding2px margin0 backgroundefe div colorred fieldset margin1px padding3px

HTML

ltformgt ltdivgtForm is surrounded by the green outl ineltdivgt ltlabelgtChildltlabelgt ltinput name=name gt

ltfieldsetgt ltlabelgtGrandchildltlabelgt ltinput name=newsletter gt ltfieldsetgt

ltformgt Sibling to form ltinput name=none gt

multiple $(selector1 selector2 selectorN)

Selects the combined results of all the specif ied selectors

Added in version 10

$(selector1 selector2 selectorN)

selector1Selector Any valid selector

selector2Selector Another valid selector

selectorNSelector (opt ional) As many more valid selectors as you like

You can specify any number of selectors to combine into a single result This mult ipleexpression combinator is an ef f icient way to select disparate elements The order of the DOMelements in the returned jQuery object may not be ident ical as they will be in document orderAn alternat ive to this combinator is the add() method

Example 1 Finds the elements that match any of these three selectors

Javascript

$(divspanpmyClass)css(border3px solid red)

HTML

ltdivgtdivltdivgt

ltp class=myClassgtp class=myClassltpgt ltp class=notMyClassgtp class=notMyClassltpgt ltspangtspanltspangt

CSS

divspanp width 126px height 60px floatleft padding 3px margin 2px background-color EEEEEE font-size14px

Example 2 Show the order in the jQuery object

Javascript

var l ist = $(divpspan)map(function () return thistagName )get()join( ) $(b)append(documentcreateTextNode(list))

CSS

b colorred font-size16px displayblock clearleft divspanp width 40px height 40px floatleft margin 10px background-color blue padding3px colorwhite

HTML

ltspangtspanltspangt

ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt ltspangtspanltspangt

ltpgtpltpgt ltdivgtdivltdivgt ltbgtltbgt

all $()

Selects all elements

Added in version 10

$()

Caut ion The all or universal selector is extremely slow except when used by itself

Example 1 Finds every element (including head body etc) in the document

Javascript

var elementCount = $()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

HTML

ltdivgtDIVltdivgt

ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgt

CSS

h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE

Example 2 A common way to select all elements is to f ind within documentbody so elementslike head script etc are lef t out

Javascript

var elementCount = $(test)find()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

HTML

ltdiv id=testgt ltdivgtDIVltdivgt ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgtltdivgt

CSS

h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE test width auto height auto background-color transparent

class $(class)

Selects all elements with the given class

Added in version 10

$(class)

classString A class to search for An element can have mult iple classes only one ofthem must match

For class selectors jQuery uses JavaScript s nat ive getElementsByClassName() funct ion if thebrowser supports it

Example 1 Finds the element with the class myClass

Javascript

$(myClass)css(border3px solid red)

HTML

ltdiv class=notMegtdiv class=notMeltdivgt

ltdiv class=myClassgtdiv class=myClassltdivgt ltspan class=myClassgtspan class=myClassltspangt

CSS

divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

Example 2 Finds the element with both myclass and otherclass classes

Javascript

$(myclassotherclass)css(border13px solid red)

HTML

ltdiv class=myclassgtdiv class=notMeltdivgt

ltdiv class=myclass otherclassgtdiv class=myClassltdivgt ltspan class=myclass otherclassgtspan class=myClassltspangt

CSS

divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

element $(element)

Selects all elements with the given tag name

Added in version 10

$(element)

elementString An element to search for Refers to the tagName of DOM nodes

JavaScript s getElementsByTagName() funct ion is called to return the appropriate elementswhen this expression is used

Example 1 Finds every DIV element

Javascript

$(div)css(border9px solid red)

HTML

ltdivgtDIV1ltdivgt

ltdivgtDIV2ltdivgt ltspangtSPANltspangt

CSS

divspan width 60px height 60px floatleft padding 10px margin 10px background-color EEEEEE

id $(id)

Selects a single element with the given id at t ribute

Added in version 10

$( id)

idString An ID to search for specif ied via the id at t ribute of an element

For id selectors jQuery uses the JavaScript funct ion documentgetElementById() which isextremely ef f icient When another selector is at tached to the id selector such as h2pageTit lejQuery performs an addit ional check before ident ifying the element as a match

As always remember that as a developer your time is typically the most valuableresource Do not focus on optimization of selector speed unless it is clear thatperformance needs to be improved

Each id value must be used only once within a document If more than one element has beenassigned the same ID queries that use that ID will only select the f irst matched element in theDOM This behavior should not be relied on however a document with more than one elementusing the same ID is invalid

If the id contains characters like periods or colons you have to escape those characters withbackslashes

Example 1 Finds the element with the id myDiv

Javascript

$(myDiv)css(border3px solid red)

HTML

ltdiv id=notMegtltpgtid=notMeltpgtltdivgt

ltdiv id=myDivgtid=myDivltdivgt

CSS

div width 90px height 90px floatleft padding 5px margin 5px background-color EEEEEE

Example 2 Finds the element with the id myIDentry[1] See how certain characters must beescaped with backslashes

Javascript

$(myIDentry[1])css(border3px solid red)

HTML

ltdiv id=myIDentry[0]gtid=myIDentry[0]ltdivgt

ltdiv id=myIDentry[1]gtid=myIDentry[1]ltdivgt ltdiv id=myIDentry[2]gtid=myIDentry[2]ltdivgt

CSS

div width 300px floatleft padding 2px margin 3px background-color EEEEEE

Traversing

has

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

Added in version 14

has(contained)jQuery

containedElement A DOM element to match elements against

Given a jQuery object that represents a set of DOM elements the has() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst the descendants of the matching elements the element will be included in the result ifany of its descendant elements matches the selector

Consider a page with a nested list as follows

ltulgt ltligtlist item 1ltligt ltligtlist item 2 ltulgt ltligtlist item 2-altligt ltligtlist item 2-bltligt ltulgt ltl igt ltligtlist item 3ltligt ltligtlist item 4ltligtltulgt

We can apply this method to the set of list items as follows

$( l i )has(ul )css(background-color red)

The result of this call is a red background for item 2 as it is the only ltligt that has a ltulgt amongits descendants

Example 1 Check if an element is inside another

Javascript

$(ul)append(ltligt + ($(ul)has(l i)length Yes No) + ltl igt) $(ul)has(l i)addClass(full)

CSS

ful l border 1px solid red

HTML

ltulgtltligtDoes the UL contain an LIltl igtltulgt

parentsUntil

Get the ancestors of each element in the current set of matched elements up to but notincluding the element matched by the selector DOM node or jQuery object

Added in version 16

parentsUnt il(element f ilter)jQuery

elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching ancestor elements

f ilterSelector (opt ional) A string containing a selector expression to matchelements against

Given a selector expression that represents a set of DOM elements the parentsUnt il() methodtraverses through the ancestors of these elements unt il it reaches an element matched by theselector passed in the methods argument The result ing jQuery object contains all of theancestors up to but not including the one matched by the parentsUnt il() selector

If the selector is not matched or is not supplied all ancestors will be selected in these cases itselects the same elements as the parents() method does when no selector is provided

As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstparentsUnt il() argument

The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

Example 1 Find the ancestors of

up to

and give them a red background color Also f ind ancestors of

that have a class of yes up toand give them a green border

Javascript

$(l i item-a)parentsUntil(level-1) css(background-color red)

$(l i item-2)parentsUntil( $(ullevel-1) yes ) css(border 3px solid green)

HTML

ltul class=level-1 yesgt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2 yesgt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

prevUntil

Get all preceding siblings of each element up to but not including the element matched by theselector DOM node or jQuery object

Added in version 16

prevUnt il(element f ilter)jQuery

elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching preceding sibling elements

f ilterSelector (opt ional) A string containing a selector expression to matchelements against

Given a selector expression that represents a set of DOM elements the prevUnt il() methodsearches through the predecessors of these elements in the DOM tree stopping when itreaches an element matched by the methods argument The new jQuery object that isreturned contains all previous siblings up to but not including the one matched by theprevUnt il() selector the elements are returned in order f rom the closest sibling to the farthest

If the selector is not matched or is not supplied all previous siblings will be selected in thesecases it selects the same elements as the prevAll() method does when no f ilter selector isprovided

As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstprevUnt il() argument

The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

Example 1 Find the siblings that precede

up to the precedingand give them a red background color Also f ind previous

siblings ofup toand give them a green text color

Javascript

$(term-2)prevUntil(dt) css(background-color red) var term1 = documentgetElementById(term-1)$(term-3)prevUntil(term1 dd) css(color green)

HTML

ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

nextUntil

Get all following siblings of each element up to but not including the element matched by theselector DOM node or jQuery object passed

Added in version 16

nextUnt il(element f ilter)jQuery

elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching following sibling elements

f ilterSelector (opt ional) A string containing a selector expression to matchelements against

Given a selector expression that represents a set of DOM elements the nextUnt il() methodsearches through the successors of these elements in the DOM tree stopping when it reachesan element matched by the methods argument The new jQuery object that is returnedcontains all following siblings up to but not including the one matched by the nextUnt il()argument

If the selector is not matched or is not supplied all following siblings will be selected in thesecases it selects the same elements as the nextAll() method does when no f ilter selector isprovided

As of jQuery 16 A DOM node or jQuery object instead of a selector may be passed to thenextUnt il() method

The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

Example 1 Find the siblings that follow

up to the nextand give them a red background color Also f ind

siblings that followup toand give them a green text color

Javascript

$(term-2)nextUntil(dt) css(background-color red)

var term3 = documentgetElementById(term-3)$(term-1)nextUntil(term3 dd) css(color green)

HTML

ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

each

Iterate over a jQuery object execut ing a funct ion for each matched element

Added in version 10

each(funct ion(index Element))jQuery

funct ion(index Element)Funct ion A funct ion to execute for each matched element

The each() method is designed to make DOM looping constructs concise and less error-proneWhen called it iterates over the DOM elements that are part of the jQuery object Each t ime thecallback runs it is passed the current loop iterat ion beginning from 0 More important ly thecallback is f ired in the context of the current DOM element so the keyword this refers to theelement

Suppose we had a simple unordered list on the page

ltulgt ltligtfooltligt ltligtbarltligt ltulgt

We can select the list items and iterate across them

$( l i )each(function(index) alert(index + + $(this)text()) )

A message is thus alerted for each item in the list

0 foo

1 bar

We can stop the loop from within the callback funct ion by returning false

Example 1 Iterates over three divs and sets their color property

Javascript

$(documentbody)cl ick(function () $(div)each(function (i) i f (thisstylecolor = blue) thisstylecolor = blue else thisstylecolor = ) )

CSS

div colorred text-aligncenter cursorpointer font-weightbolder width300px

HTML

ltdivgtClick hereltdivgt

ltdivgtto iterate throughltdivgt ltdivgtthese divsltdivgt

Example 2 If you want to have the jQuery object instead of the regular DOM element use the$(this) funct ion for example

Javascript

$(span)cl ick(function () $(l i)each(function() $(this)toggleClass(example) ) )

CSS

ul font-size18px margin0 span colorblue text-decorationunderline cursorpointer example font-styleital ic

HTML

To do l ist ltspangt(click here to change)ltspangt ltulgt ltligtEatltligt ltligtSleepltligt

ltligtBe merryltligt ltulgt

Example 3 You can use return to break out of each() loops early

Javascript

$(button)cl ick(function () $(div)each(function (index domEle) domEle == this $(domEle)css(backgroundColor yellow) i f ($(this)is(stop)) $(span)text(Stopped at div index + index) return false ) )

CSS

div width40px height40px margin5px floatleft border2px blue solid text-aligncenter span colorred

HTML

ltbuttongtChange colorsltbuttongt ltspangtltspangt ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdiv id=stopgtStop hereltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt

first

Reduce the set of matched elements to the f irst in the set

Added in version 14

f irst()jQuery

[

Given a jQuery object that represents a set of DOM elements the f irst() method constructs anew jQuery object f rom the f irst matching element

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

We can apply this method to the set of list items

$( l i )first()css(background-color red)

The result of this call is a red background for the f irst item

Example 1 Highlight the f irst span in a paragraph

CSS

highlightbackground-color yellow

Javascript

$(p span)first()addClass(highlight)

HTML

ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

last

Reduce the set of matched elements to the f inal one in the set

Added in version 14

last()jQuery

[

Given a jQuery object that represents a set of DOM elements the last() method constructs anew jQuery object f rom the last matching element

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

We can apply this method to the set of list items

$( l i )last()css(background-color red)

The result of this call is a red background for the f inal item

Example 1 Highlight the last span in a paragraph

CSS

highlightbackground-color yellow

Javascript

$(p span)last()addClass(highlight)

HTML

ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

slice

Reduce the set of matched elements to a subset specif ied by a range of indices

Added in version 114

slice(start end)jQuery

start Integer An integer indicat ing the 0-based posit ion at which the elements begin tobe selected If negat ive it indicates an of fset f rom the end of the set

endInteger (opt ional) An integer indicat ing the 0-based posit ion at which theelements stop being selected If negat ive it indicates an of fset f rom theend of the set If omit ted the range cont inues unt il the end of the set

Given a jQuery object that represents a set of DOM elements the slice() method constructs anew jQuery object f rom a subset of the matching elements The supplied start index ident if iesthe posit ion of one of the elements in the set if end is omit ted all elements af ter this one willbe included in the result

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

We can apply this method to the set of list items

$( l i )sl ice(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 iszero-based and refers to the posit ion of elements within the jQuery object not within theDOM tree

The end parameter allows us to limit the selected range even further For example

$( l i )sl ice(2 4)css(background-color red)

Now only items 3 and 4 are selected The index is once again zero-based the range extends upto but not including the specif ied index

Negative Indices

The jQuery slice() method is patterned af ter the JavaScript slice() method for arrays One ofthe features that it mimics is the ability for negat ive numbers to be passed as either the start orend parameter If a negat ive number is provided this indicates a posit ion start ing f rom the endof the set rather than the beginning For example

$( l i )sl ice(-2 -1)css(background-color red)

This t ime only list item 4 is turned red since it is the only item in the range between two fromthe end (-2) and one from the end (-1)

Example 1 Turns divs yellow based on a random slice

Javascript

function colorEm() var $div = $(div) var start = Mathfloor(Mathrandom() $divlength) var end = Mathfloor(Mathrandom() ($divlength - start)) + start + 1 i f (end == $divlength) end = undefined $divcss(background ) i f (end) $divsl ice(start end)css(background yellow) else $divsl ice(start)css(background yellow) $(span)text($(div)sl ice( + start + (end + end ) + )css(background yellow))

$(button)cl ick(colorEm)

CSS

div width40px height40px margin10px floatleft border2px solid blue span colorred font-weightbold button margin5px

HTML

ltpgtltbuttongtTurn sl ice yellowltbuttongt ltspangtClick the buttonltspangtltpgt ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt

Example 2 Selects all paragraphs then slices the select ion to include only the f irst element

Javascript

$(p)sl ice(0 1)wrapInner(ltbgtltbgt)

Example 3 Selects all paragraphs then slices the select ion to include only the f irst and secondelement

Javascript

$(p)sl ice(0 2)wrapInner(ltbgtltbgt)

Example 4 Selects all paragraphs then slices the select ion to include only the second element

Javascript

$(p)sl ice(1 2)wrapInner(ltbgtltbgt)

Example 5 Selects all paragraphs then slices the select ion to include only the second and thirdelement

Javascript

$(p)sl ice(1)wrapInner(ltbgtltbgt)

Example 6 Selects all paragraphs then slices the select ion to include only the third element

Javascript

$(p)sl ice(-1)wrapInner(ltbgtltbgt)

end

End the most recent f iltering operat ion in the current chain and return the set of matchedelements to its previous state

Added in version 10

end()jQuery

Most of jQuerys DOM traversal methods operate on a jQuery object instance and produce anew one matching a dif ferent set of DOM elements When this happens it is as if the new setof elements is pushed onto a stack that is maintained inside the object Each successivef iltering method pushes a new element set onto the stack If we need an older element set wecan use end() to pop the sets back of f of the stack

Suppose we have a couple short lists on a page

ltul class=firstgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgtltul class=secondgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgt

The end() method is useful primarily when exploit ing jQuerys chaining propert ies When notusing chaining we can usually just call up a previous object by variable name so we dont needto manipulate the stack With end() though we can string all the method calls together

$(ulfirst)find(foo)css(background-color red) end()find(bar)css(background-color green)

This chain searches for items with the class foo within the f irst list only and turns theirbackgrounds red Then end() returns the object to its state before the call to f ind() so thesecond f ind() looks for bar inside ltul class=f irstgt not just inside that list s ltli class=foogtand turns the matching elements backgrounds green The net result is that items 1 and 3 ofthe f irst 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 f iltering methodsproviding the openings of nested blocks and end() methods closing them

$(ulfirst)find(foo) css(background-color red)end()find(bar) css(background-color green)end()

The last end() is unnecessary as we are discarding the jQuery object immediately thereafterHowever when the code is writ ten in this form the end() provides visual symmetry and a senseof complet ion acirceurordquomaking the program at least to the eyes of some developers more readableat the cost of a slight hit to performance as it is an addit ional funct ion call

Example 1 Selects all paragraphs f inds span elements inside these and reverts the select ionback to the paragraphs

Javascript

jQueryfnshowTags = function (n) var tags = thismap(function () return thistagName ) get()join( ) $(beq( + n + ))text(tags) return this

$(p)showTags(0) find(span) showTags(1) css(background yellow) end() showTags(2) css(font-style ital ic)

CSS

p div margin1px padding1px font-weightbold font-size16px div colorblue b colorred

HTML

ltpgt Hi there ltspangthowltspangt are you ltspangtdoingltspangt ltpgt

ltpgt This ltspangtspanltspangt is one of several ltspangtspansltspangt in this ltspangtsentenceltspangt ltpgt

ltdivgt Tags in jQuery object initial ly ltbgtltbgt ltdivgt ltdivgt Tags in jQuery object after find ltbgtltbgt

ltdivgt ltdivgt Tags in jQuery object after end ltbgtltbgt ltdivgt

Example 2 Selects all paragraphs f inds span elements inside these and reverts the select ion

back to the paragraphs

Javascript

$(p)find(span)end()css(border 2px red solid)

CSS

p margin10px padding10px

HTML

ltpgtltspangtHelloltspangt how are youltpgt

andSelf

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

Added in version 12

andSelf()jQuery

As described in the discussion for end() jQuery objects maintain an internal stack that keepstrack of changes to the matched set of elements When one of the DOM traversal methods iscalled the new set of elements is pushed onto the stack If the previous set of elements isdesired as well andSelf() can help

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

The result of the following code is a red background behind items 3 4 and 5

$( l i third-item)nextAll()andSelf() css(background-color red)

First the init ial selector locates item 3 init ializing the stack with the set containing just this itemThe call to nextAll() then pushes the set of items 4 and 5 onto the stack Finally the andSelf()invocat ion merges these two sets together creat ing a jQuery object that points to all three

items in document order [ltlithird-itemgtltligtltligt ]

Example 1 Find all divs and all the paragraphs inside of them and give them both class namesNot ice the div doesnt have the yellow background color since it didnt use andSelf()

Javascript

$(div)find(p)andSelf()addClass(border) $(div)find(p)addClass(background)

CSS

p div margin5px padding5px border border 2px solid red background backgroundyellow

HTML

ltdivgt ltpgtFirst Paragraphltpgt ltpgtSecond Paragraphltpgt ltdivgt

siblings

Get the siblings of each element in the set of matched elements opt ionally f iltered by aselector

Added in version 10

siblings(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the siblings() method allows usto search through the siblings of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

If we begin at the third item we can f ind its siblings

$( l i 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 aselector expression all of the siblings are part of the object If we had supplied one only thematching items among these four would be included

The original element is not included among the siblings which is important to remember whenwe wish to f ind all elements at a part icular level of the DOM tree

Example 1 Find the unique siblings of all yellow li elements in the 3 lists (including other yellow lielements if appropriate)

Javascript

var len = $(hil ite)siblings() css(color red) length $(b)text(len)

CSS

ul floatleft margin5px font-size16px font-weightbold p colorblue margin10px 20px font-size16px padding5px font-weightbolder hi l ite backgroundyellow

HTML

ltulgt ltligtOneltligt

ltligtTwoltligt ltli class=hil itegtThreeltligt ltligtFourltligt ltulgt

ltulgt ltligtFiveltligt ltligtSixltligt ltligtSevenltligt

ltulgt ltulgt ltligtEightltligt ltli class=hil itegtNineltligt

ltligtTenltligt ltli class=hil itegtElevenltligt ltulgt ltpgtUnique siblings ltbgtltbgtltpgt

Example 2 Find all siblings with a class selected of each div

Javascript

$(p)siblings(selected)css(background yellow)

HTML

ltdivgtltspangtHelloltspangtltdivgt

ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

prevAll

Get all preceding siblings of each element in the set of matched elements opt ionally f iltered bya selector

Added in version 12

prevAll(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the prevAll() method searchesthrough the predecessors of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements the elements are returned in order beginning with theclosest sibling

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

If we begin at the third item we can f ind the elements which come before it

$( l i 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 aselector 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

Example 1 Locate all the divs preceding the last div and give them a class

Javascript

$(divlast)prevAll()addClass(before)

CSS

div width70px height70px backgroundabc border2px solid black margin10px floatleft divbefore border-color red

HTML

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

prev

Get the immediately preceding sibling of each element in the set of matched elementsopt ionally f iltered by a selector

Added in version 10

prev(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the prev() method allows us tosearch through the predecessors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

If we begin at the third item we can f ind the element which comes just before it

$( l i 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 selectorexpression this preceding element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

Example 1 Find the very previous sibling of each div

Javascript

var $curr = $(start) $currcss(background f99) $(button)cl ick(function () $curr = $currprev() $(div)css(background ) $currcss(background f99) )

CSS

div width40px height40px margin10px floatleft border2px blue solid padding2px span font-size14px p clearleft margin10px

HTML

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltspangthas childltspangtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdiv id=startgtltdivgt

ltdivgtltdivgt ltpgtltbuttongtGo to Prevltbuttongtltpgt

Example 2 For each paragraph f ind the very previous sibling that has a class selected

Javascript

$(p)prev(selected)css(background yellow)

HTML

ltdivgtltspangtHelloltspangtltdivgt

ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

parents

Get the ancestors of each element in the current set of matched elements opt ionally f iltered

by a selector

Added in version 10

parents(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the parents() method allows usto search through the ancestors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements ordered from immediate parent on up the elementsare returned in order f rom the closest parent to the outer ones The parents() and parent()methods are similar except that the lat ter only t ravels a single level up the DOM tree

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a basic nested list on it

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

If we begin at item A we can f ind its ancestors

$( l i 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 onup the DOM tree all the way to the lthtmlgt element) Since we do not supply a selectorexpression 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

Example 1 Find all parent elements of each b

Javascript

var parentEls = $(b)parents() map(function () return thistagName ) get()join( )$(b)append(ltstronggt + parentEls + ltstronggt)

CSS

b span p html body padding 5em border 1px solid b colorblue strong colorred

HTML

ltdivgt ltpgt ltspangt ltbgtMy parents are ltbgt ltspangt

ltpgt ltdivgt

Example 2 Click to f ind all unique div parent elements of each span

Javascript

function showParents() $(div)css(border-color white) var len = $(spanselected) parents(div) css(border 2px red solid) length $(b)text(Unique div parents + len)$(span)cl ick(function () $(this)toggleClass(selected) showParents())

CSS

p div span margin2px padding1px div border2px white solid span cursorpointer font-size12px selected colorblue b colorred displayblock font-size14px

HTML

ltpgt ltdivgt ltdivgtltspangtHelloltspangtltdivgt ltspangtHello Againltspangt

ltdivgt ltdivgt ltspangtAnd Hello Againltspangt ltdivgt ltpgt

ltbgtClick Hellos to toggle their parentsltbgt

parent

Get the parent of each element in the current set of matched elements opt ionally f iltered by aselector

Added in version 10

parent(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the parent() method allows usto search through the parents of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements The parents() and parent() methods are similar exceptthat the lat ter only t ravels a single level up the DOM tree

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a basic nested list on it

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

If we begin at item A we can f ind its parents

$( l i 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 selectorexpression the parent element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

Example 1 Shows the parent of each element as (parent gt child) Check the View Source tosee the raw html

Javascript

$( documentbody)each(function () var parentTag = $(this)parent()get(0)tagName $(this)prepend(documentcreateTextNode(parentTag + gt )) )

CSS

divp margin10px

HTML

ltdivgtdiv ltspangtspan ltspangt ltbgtb ltbgt

ltdivgt ltpgtp ltspangtspan ltemgtem ltemgt ltspangt ltpgt

ltdivgtdiv ltstronggtstrong ltspangtspan ltspangt ltemgtem ltbgtb ltbgt ltemgt

ltstronggt ltbgtb ltbgt ltdivgt

Example 2 Find the parent element of each paragraph with a class selected

Javascript

$(p)parent(selected)css(background yellow)

HTML

ltdivgtltpgtHelloltpgtltdivgt

ltdiv class=selectedgtltpgtHello Againltpgtltdivgt

offsetParent

Get the closest ancestor element that is posit ioned

Added in version 126

offsetParent()jQuery

Given a jQuery object that represents a set of DOM elements the of fsetParent() methodallows us to search through the ancestors of these elements in the DOM tree and construct anew jQuery object wrapped around the closest posit ioned ancestor An element is said to beposit ioned if it has a CSS posit ion at t ribute of relat ive absolute or f ixed This informat ion isuseful for calculat ing of fsets for performing animat ions and placing objects on the page

Consider a page with a basic nested list on it with a posit ioned element

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

If we begin at item A we can f ind its posit ioned ancestor

$( l i item-a)offsetParent()css(background-color red)

This will change the color of list item II which is posit ioned

Example 1 Find the of fsetParent of item A

Javascript

$( l i item-a)offsetParent()css(background-color red)

HTML

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igt ltulgt

nextAll

Get all following siblings of each element in the set of matched elements opt ionally f iltered bya selector

Added in version 12

nextAll(selector)jQuery

selectorString (opt ional) A string containing a selector expression to match elementsagainst

Given a jQuery object that represents a set of DOM elements the nextAll() method allows usto search through the successors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

If we begin at the third item we can f ind the elements which come after it

$( l i 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 aselector 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

Example 1 Locate all the divs af ter the f irst and give them a class

Javascript

$(divfirst)nextAll()addClass(after)

CSS

div width 80px height 80px background abc border 2px solid black margin 10px float left divafter border-color red

HTML

ltdivgtfirstltdivgt ltdivgtsiblingltdivgtchildltdivgtltdivgt ltdivgtsiblingltdivgt

ltdivgtsiblingltdivgt

Example 2 Locate all the paragraphs af ter the second child in the body and give them a class

Javascript

$(nth-child(1))nextAll(p)addClass(after)

CSS

div p width 60px height 60px background abc border 2px solid black margin 10px float left after border-color red

HTML

ltpgtpltpgt

ltdivgtdivltdivgt ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt

ltpgtpltpgt ltdivgtdivltdivgt

next

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

Added in version 10

next(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the next() method allows us tosearch through the immediately following sibling of these elements in the DOM tree andconstruct a new jQuery object f rom the matching elements

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the immediately following sibling matches the selector it remains in the newlyconstructed jQuery object otherwise it is excluded

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

If we begin at the third item we can f ind the element which comes just af ter it

$( l i 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 hadsupplied one the element would be tested for a match before it was included

Example 1 Find the very next sibling of each disabled button and change its text this button isdisabled

Javascript

$(button[disabled])next()text(this button is disabled)

CSS

span colorblue font-weightbold button width100px

HTML

ltdivgtltbutton disabled=disabledgtFirstltbuttongt - ltspangtltspangtltdivgt ltdivgtltbuttongtSecondltbuttongt - ltspangtltspangtltdivgt

ltdivgtltbutton disabled=disabledgtThirdltbuttongt - ltspangtltspangtltdivgt

Example 2 Find the very next sibling of each paragraph Keep only the ones with a classselected

Javascript

$(p)next(selected)css(background yellow)

HTML

ltpgtHelloltpgt

ltp class=selectedgtHello Againltpgt ltdivgtltspangtAnd Againltspangtltdivgt

find

Get the descendants of each element in the current set of matched elements f iltered by aselector jQuery object or element

Added in version 16

f ind(element)jQuery

elementElement An element to match elements against

Given a jQuery object that represents a set of DOM elements the f ind() method allows us tosearch through the descendants of these elements in the DOM tree and construct a newjQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree

The f irst signature for the f ind()method accepts a selector expression of the same type thatwe can pass to the $() funct ion The elements will be f iltered by test ing whether they match thisselector

Consider a page with a basic nested list on it

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

If we begin at item II we can f ind list items within it

$( l i item-ii )find( l i )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 IImatches the selector expression it is not included in the results only descendants areconsidered candidates for the match

Unlike in the rest of the tree traversal methods the selector expression is requiredin a call to find() If we need to retrieve all of the descendant elements we canpass in the universal selector to accomplish this

Selector context is implemented with the f ind() method therefore $(liitem-ii)f ind(li) isequivalent to $(li liitem-ii)

As of jQuery 16 we can also f ilter the select ion with a given jQuery collect ion or element Withthe same nested list as above if we start with

var $allListElements = $( l i )

And then pass this jQuery object to f ind

$( l i item-ii )find( $allListElements )

This will return a jQuery collect ion which contains only the list elements that are descendantsof item II

Similarly an element may also be passed to f ind

var item1 = $( l i item-1)[0]$( l i item-ii )find( item1 )css(background-color red)

The result of this call would be a red background on item 1

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

Javascript

$(p)find(span)css(color red)

HTML

ltpgtltspangtHelloltspangt how are youltpgtltpgtMe Im ltspangtgoodltspangtltpgt

Example 2 A select ion using a jQuery collect ion of all span tags Only spans within p tags arechanged to red while others are lef t blue

CSS

span color blue

Javascript

var $spans = $(span) $(p)find( $spans )css(color red)

HTML

ltpgtltspangtHelloltspangt how are youltpgt ltpgtMe Im ltspangtgoodltspangtltpgt ltdivgtDid you ltspangteatltspangt yetltdivgt

Example 3 Add spans around each word then add a hover and italicize words with the let ter t

Javascript

var newText = $(p)text()split( )join(ltspangt ltspangt) newText = ltspangt + newText + ltspangt

$(p)html( newText ) find(span) hover(function() $(this)addClass(hil ite) function() $(this)removeClass(hil ite) ) end() find(contains(t)) css(font-style ital ic font-weightbolder)

CSS

p font-size20px width200px cursordefault colorblue font-weightbold margin0 10px hi l ite backgroundyellow

HTML

ltpgt When the day is short find that which matters to you or stop believing ltpgt

contents

Get the children of each element in the set of matched elements including text and commentnodes

Added in version 12

contents()jQuery

Given a jQuery object that represents a set of DOM elements the contents() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The contents() and children() methods aresimilar except that the former includes text nodes as well as HTML elements in the result ingjQuery object

The contents() method can also be used to get the content document of an if rame if theif rame is on the same domain as the main page

Consider a simple ltdivgt with a number of text nodes each of which is separated by two linebreak elements (ltbr gt)

ltdiv class=containergt Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ltbr gtltbr gt Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut al iquip ex ea commodo consequat ltbr gt ltbr gt Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariaturltdivgt

We can employ the contents() method to help convert this blob of text into three well-formedparagraphs

$(container)contents()fi lter(function() return thisnodeType == 3) wrap(ltpgtltpgt)end()fi lter(br) remove()

This code f irst retrieves the contents of ltdiv class=containergt and then f ilters it for textnodes which are wrapped in paragraph tags This is accomplished by test ing the nodeTypeproperty of the element This DOM property holds a numeric code indicat ing the nodes typetext nodes use the code 3 The contents are again f iltered this t ime for ltbr gt elements andthese elements are removed

Example 1 Find all the text nodes inside a paragraph and wrap them with a bold tag

Javascript

$(p)contents()fi lter(function() return thisnodeType = 1 )wrap(ltbgt)

HTML

ltpgtHello lta href=httpejohnorggtJohnltagt how are you doingltpgt

Example 2 Change the background colour of links inside of an if rame

Javascript

$(frameDemo)contents()find(a)css(background-colorBADA55)

HTML

ltiframe src=httpapijquerycom width=80 height=600 id=frameDemogtltiframegt

closest

Get the f irst ancestor element that matches the selector beginning at the current element andprogressing up through the DOM tree

Added in version 16

closest(element)jQuery

elementElement An element to match elements against

Given a jQuery object that represents a set of DOM elements the closest() method allows usto search through these elements and their ancestors in the DOM tree and construct a newjQuery object f rom the matching elements The parents() and closest() methods are similar inthat they both t raverse up the DOM tree The dif ferences between the two though subt le aresignif icant

closest() parents()

Begins with thecurrent element

Begins with the parent element

Travels up the DOMtree unt il it f inds amatch for the suppliedselector

Travels up the DOM tree to the document s root elementadding each ancestor element to a temporary collect ion it thenf ilters that collect ion based on a selector if one is supplied

The returned jQueryobject contains zeroor one element

The returned jQuery object contains zero one or mult ipleelements

ltul id=one class=level-1gt ltli class=item-igtIltl igt ltli id=ii class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

Suppose we perform a search for ltulgt elements start ing at item A

$( l i item-a)closest(ul ) css(background-color red)

This will change the color of the level-2 ltulgt since it is the f irst encountered when traveling upthe DOM tree

Suppose we search for an ltligt element instead

$( l i item-a)closest( l i ) css(background-color red)

This will change the color of list item A The closest() method begins its search with theelement itself before progressing up the DOM tree and stops when item A matches theselector

We can pass in a DOM element as the context within which to search for the closest element

var l istItemII = documentgetElementById( i i )$( l i item-a)closest(ul l istItemII) css(background-color red)$( l i item-a)closest(one l istItemII) css(background-color green)

This will change the color of the level-2 ltulgt because it is both the f irst ltulgt ancestor of listitem A and a descendant of list item II It will not change the color of the level-1 ltulgt howeverbecause it is not a descendant of list item II

Example 1 Show how event delegat ion can be done with closest The closest list elementtoggles a yellow background when it or its descendent is clicked

Javascript

$( document )bind(click function( e ) $( etarget )closest(l i)toggleClass(hil ight) )

CSS

l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

HTML

ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

Example 2 Pass a jQuery object to closest The closest list element toggles a yellowbackground when it or its descendent is clicked

Javascript

var $listElements = $(l i)css(color blue) $( document )bind(click function( e ) $( etarget )closest( $listElements )toggleClass(hil ight) )

CSS

l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

HTML

ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

closest

Gets an array of all the elements and selectors matched against the current element upthrough the DOM tree

Added in version 14

closest(selectors context)Array

selectorsArray An array or string containing a selector expression to match elementsagainst (can also be a jQuery object)

context Element (opt ional) A DOM element within which a matching element may befound If no context is passed in then the context of the jQuery setwill be used instead

This method is primarily meant to be used internally or by plugin authors

Example 1 Show how event delegat ion can be done with closest

Javascript

var close = $(l i first)closest([ul body]) $each(close function(i) $(l i)eq(i)html( thisselector + + thiselemnodeName ) )

CSS

HTML

ltulgtltligtltligtltligtltligtltulgt

children

Get the children of each element in the set of matched elements opt ionally f iltered by aselector

Added in version 10

children(selector)jQuery

selectorSelector (opt ional) A string containing a selector expression to matchelements against

Given a jQuery object that represents a set of DOM elements the children() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree Note also that like mostjQuery methods children() does not return text nodes to get all children including text andcomment nodes use contents()

The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

Consider a page with a basic nested list on it

ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

If we begin at the level-2 list we can f ind its children

$(ullevel-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 aselector expression all of the children are part of the returned jQuery object If we had suppliedone only the matching items among these three would be included

Example 1 Find all children of the clicked element

Javascript

$(container)cl ick(function (e) $()removeClass(hil ite) var $kids = $(etarget)children() var len = $kidsaddClass(hil ite)length

$(results spanfirst)text(len) $(results spanlast)text(etargettagName)

epreventDefault() return false )

CSS

body font-size16px font-weightbolder div width130px height82px margin10px floatleft border1px solid blue padding4px container widthauto height105px margin0 floatnone bordernone hi l ite border-colorred results displayblock colorred p margin10px border1px solid transparent span colorblue border1px solid transparent input width100px em border1px solid transparent a border1px solid transparent b border1px solid transparent button border1px solid transparent

HTML

ltdiv id=containergt

ltdivgt ltpgtThis ltspangtis the ltemgtwayltemgt weltspangt write ltemgttheltemgt demoltpgt

ltdivgt ltdivgt lta href=gtltbgtwltbgtritltbgteltbgtltagt the ltspangtdemoltspangt ltbuttongtwrite theltbuttongt demo ltdivgt

ltdivgt This ltspangtthe way we ltemgtwriteltemgt the ltemgtdemoltemgt soltspangt

ltinput type=text value=early gt in ltdivgt ltpgt ltspangttltspangthe ltspangtmltspangtorning ltspan id=resultsgtFound ltspangt0ltspangt children in ltspangtTAGltspangtltspangt

ltpgt ltdivgt

Example 2 Find all children of each div

Javascript

$(div)children()css(border-bottom 3px double red)

CSS

body font-size16px font-weightbolder span colorblue p margin5px 0

HTML

ltpgtHello (this is a paragraph)ltpgt

ltdivgtltspangtHello Again (this span is a child of the a div)ltspangtltdivgt ltpgtAnd ltspangtAgainltspangt (in another paragraph)ltpgt

ltdivgtAnd One Last ltspangtTimeltspangt (most text directly in a div)ltdivgt

Example 3 Find all children with a class selected of each div

Javascript

$(div)children(selected)css(color blue)

CSS

body font-size16px font-weightbolder p margin5px 0

HTML

ltdivgt ltspangtHelloltspangt ltp class=selectedgtHello Againltpgt ltdiv class=selectedgtAnd Againltdivgt

ltpgtAnd One Last Timeltpgt ltdivgt

add

Add elements to the set of matched elements

Added in version 14

add(selector context)jQuery

selectorSelector A string represent ing a selector expression to f ind addit ionalelements to add to the set of matched elements

context Element The point in the document at which the selector should beginmatching similar to the context argument of the $(selector context)method

Given a jQuery object that represents a set of DOM elements the add() method constructs anew jQuery object f rom the union of those elements and the ones passed into the methodThe argument to add() can be pret ty much anything that $() accepts including a jQueryselector 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 avariable for later use For example

$(p)add(div)addClass(widget)var pdiv = $(p)add(div)

The following will not save the added elements because the add() method creates a new setand leaves the original set in pdiv unchanged

var pdiv = $(p)pdivadd(div) WRONG pdiv wil l not change

Consider a page with a simple list and a paragraph following it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligtltulgtltpgta paragraphltpgt

We can select the list items and then the paragraph by using either a selector or a reference tothe DOM element itself as the add() methods argument

$( l i )add(p)css(background-color red)

Or

$( l i )add(documentgetElementsByTagName(p)[0]) css(background-color red)

The result of this call is a red background behind all four elements Using an HTML snippet asthe add() methods argument (as in the third version) we can create addit ional elements on thef ly and add those elements to the matched set of elements Let s say for example that wewant to alter the background of the list items along with a newly created paragraph

$( l i )add(ltp id=newgtnew paragraphltpgt) css(background-color red)

Although the new paragraph has been created and its background color changed it st ill doesnot appear on the page To place it on the page we could add one of the insert ion methods tothe chain

As of jQuery 14 the results f rom add() will always be returned in document order (rather than asimple concatenat ion)

Note To reverse the add() you can use not( elements | selector ) to remove elements f rom thejQuery results or end() to return to the select ion before you added

Example 1 Finds all divs and makes a border Then adds all paragraphs to the jQuery object toset their backgrounds yellow

Javascript

$(div)css(border 2px solid red) add(p) css(background yellow)

CSS

div width60px height60px margin10px floatleft p clearleft font-weightbold font-size16px colorblue margin0 10px padding2px

HTML

ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

ltpgtAdded this (notice no border)ltpgt

Example 2 Adds more elements matched by the given expression to the set of matchedelements

Javascript

$(p)add(span)css(background yellow)

HTML

ltpgtHelloltpgtltspangtHello Againltspangt

Example 3 Adds more elements created on the f ly to the set of matched elements

Javascript

$(p)clone()add(ltspangtAgainltspangt)appendTo(documentbody)

HTML

ltpgtHelloltpgt

Example 4 Adds one or more Elements to the set of matched elements

Javascript

$(p)add(documentgetElementById(a))css(background yellow)

HTML

ltpgtHelloltpgtltspan id=agtHello Againltspangt

Example 5 Demonstrates how to add (or push) elements to an exist ing collect ion

Javascript

var collection = $(p) capture the new collectioncollection = collectionadd(documentgetElementById(a))collectioncss(background yellow)

HTML

ltpgtHelloltpgtltspan id=agtHello Againltspangt

not

Remove elements f rom the set of matched elements

Added in version 14

not(funct ion(index))jQuery

funct ion(index)Funct ion A funct ion used as a test for each element in the set this isthe current DOM element

Given a jQuery object that represents a set of DOM elements the not() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element the elements that dont match the selector will be included in the result

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

We can apply this method to the set of list items

$( l i )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 not() method allows us to remove elements f rom the matched setassuming we have found those elements previously by some other means For examplesuppose our list had an id applied to one of its items

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli id=notligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

We can fetch the third list item using the nat ive JavaScript getElementById() funct ion thenremove it f rom a jQuery object

$( l i )not(documentgetElementById(notl i )) css(background-color red)

This statement changes the color of items 1 2 4 and 5 We could have accomplished thesame thing with a simpler jQuery expression but this technique can be useful when forexample other libraries provide references to plain DOM nodes

As of jQuery 14 the not() method can take a funct ion as its argument in the same way thatf ilter() does Elements for which the funct ion returns t rue are excluded from the f iltered set allother elements are included

Example 1 Adds a border to divs that are not green or blue

Javascript

$(div)not(green blueone) css(border-color red)

CSS

div width50px height50px margin10px floatleft backgroundyellow border2px solid white green background8f8 gray backgroundccc blueone background99f

HTML

ltdivgtltdivgt ltdiv id=blueonegtltdivgt ltdivgtltdivgt ltdiv class=greengtltdivgt

ltdiv class=greengtltdivgt ltdiv class=graygtltdivgt ltdivgtltdivgt

Example 2 Removes the element with the ID selected f rom the set of all paragraphs

Javascript

$(p)not( $(selected)[0] )

Example 3 Removes the element with the ID selected f rom the set of all paragraphs

Javascript

$(p)not(selected)

Example 4 Removes all elements that match div pselected f rom the total set of allparagraphs

Javascript

$(p)not($(div pselected))

map

Pass each element in the current matched set through a funct ion producing a new jQueryobject containing the return values

Added in version 12

map(callback(index domElement))jQuery

callback(indexdomElement)Funct ion

A funct ion object that will be invoked for each element inthe current set

As the return value is a jQuery-wrapped array it s very common to get() the returned object towork with a basic array

The map() method is part icularly useful for gett ing or set t ing the value of a collect ion ofelements Consider a form with a set of checkboxes in it

ltform method=post action=gt ltfieldsetgt ltdivgt ltlabel for=twogt2ltlabelgt ltinput type=checkbox value=2 id=two name=number[]gt ltdivgt ltdivgt ltlabel for=fourgt4ltlabelgt ltinput type=checkbox value=4 id=four name=number[]gt ltdivgt ltdivgt ltlabel for=sixgt6ltlabelgt ltinput type=checkbox value=6 id=six name=number[]gt ltdivgt ltdivgt ltlabel for=eightgt8ltlabelgt ltinput type=checkbox value=8 id=eight name=number[]gt ltdivgt ltfieldsetgtltformgt

We can get a comma-separated list of checkbox IDs

$(checkbox)map(function() return thisid)get()join( )

The result of this call is the string twofoursixeight

Within the callback funct ion this refers to the current DOM element for each iterat ion Thefunct ion can return an individual data item or an array of data items to be inserted into theresult ing set If an array is returned the elements inside the array are inserted into the set If thefunct ion returns null or undef ined no element will be inserted

Example 1 Build a list of all the values within a form

Javascript

$(p)append( $(input)map(function() return $(this)val() )get()join( ) )

CSS

p colorred

HTML

ltpgtltbgtValues ltbgtltpgt ltformgt ltinput type=text name=name value=Johngt

ltinput type=text name=password value=passwordgt ltinput type=text name=url value=httpejohnorggt

ltformgt

Example 2 A contrived example to show some funct ionality

Javascript

var mappedItems = $(l i)map(function (index) var replacement = $(ltligt)text($(this)text())get(0) i f (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$(ltligt)get(0)] $(replacement[0])append(ltbgt - Altbgt) $(replacement[1])append(Extra ltbgt - Bltbgt)

replacement wil l be a dom element null or an array of dom elements return replacement)$(results)append(mappedItems)

CSS

body font-size16px ul floatleft margin0 30px colorblue results colorred

HTML

ltulgt ltligtFirstltl igt ltligtSecondltligt ltligtThirdltligt

ltligtFourthltligt ltligtFifthltligt ltulgt ltul id=resultsgt

ltulgt

Example 3 Equalize the heights of the divs

Javascript

$fnequalizeHeights = function() var maxHeight = thismap(function(ie) return $(e)height() )get() return thisheight( Mathmaxapply(this maxHeight) )

$( input)cl ick(function() $(div)equalizeHeights())

CSS

div width 40px floatleft input clearleft

HTML

ltinput type=button value=equalize div heightsgt

ltdiv style=backgroundred height 40px gtltdivgtltdiv style=backgroundgreen height 70pxgtltdivgtltdiv style=backgroundblue height 50px gtltdivgt

is

Check the current matched set of elements against a selector element or jQuery object andreturn t rue if at least one of these elements matches the given arguments

Added in version 16

is(element)Boolean

elementElement An element to match the current set of elements against

Unlike other f iltering methods is() does not create a new jQuery object Instead it allows youto test the contents of a jQuery object without modif icat ion This is of ten useful insidecallbacks such as event handlers

Suppose you have a list with two of its items containing a child element

ltulgt ltligtlist ltstronggtitem 1ltstronggtltligt ltligtltspangtlist item 2ltspangtltligt ltligtlist item 3ltligtltulgt

You can at tach a click handler to the ltulgt element and then limit the code to be triggered onlywhen a list item itself not one of its children is clicked

$(ul)cl ick(function(event) var $target = $(eventtarget) i f ( $targetis( l i) ) $targetcss(background-color red) )

Now when the user clicks on the word list in the f irst item or anywhere in the third item theclicked list item will be given a red background However when the user clicks on item 1 in thef irst item or anywhere in the second item nothing will occur because in those cases the targetof the event would be ltstronggt or ltspangt respect ively

Be aware that for selector strings with posit ional selectors such as f irst gt() or even theposit ional f iltering is done against the jQuery object passed to is() not against the containingdocument So for the HTML shown above an expression such as $(lif irst)is(lilast) returnstrue but $(lif irst-child)is(lilast-child) returns false

Using a Function

The second form of this method evaluates expressions related to elements based on afunct ion rather than a selector For each element if the funct ion returns t rue is() returns t rueas well For example given a somewhat more involved HTML snippet

ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

You can at tach a click handler to every ltligt that evaluates the number of ltstronggt elementswithin the clicked ltligt at that t ime like so

$(l i)cl ick(function() var $li = $(this) isWithTwo = $liis(function() return $(strong this)length === 2 ) i f ( isWithTwo ) $l i css(background-color green) else $l i css(background-color red) )

Example 1 Shows a few ways is() can be used inside an event handler

Javascript

$(div)one(cl ick function () i f ($(this)is(first-child)) $(p)text(Its the first div) else if ($(this)is(bluered)) $(p)text(Its a blue or red div) else if ($(this)is(contains(Peter))) $(p)text(Its Peter) else $(p)html(Its nothing ltemgtspecialltemgt) $(p)hide()sl ideDown(slow) $(this)css(border-style inset cursordefault) )

CSS

div width60px height60px margin5px floatleft border4px outset backgroundgreen text-aligncenter font-weightbolder cursorpointer blue backgroundblue red backgroundred span colorwhite font-size16px p colorred font-weightbolder backgroundyellow margin3px clearleft displaynone

HTML

ltdivgtltdivgtltdiv class=bluegtltdivgtltdivgtltdivgtltdiv class=redgtltdivgt

ltdivgtltbrgtltspangtPeterltspangtltdivgtltdiv class=bluegtltdivgtltpgtampnbspltpgt

Example 2 Returns t rue because the parent of the input is a form element

Javascript

var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

CSS

div colorred

HTML

ltformgtltinput type=checkbox gtltformgtltdivgtltdivgt

Example 3 Returns false because the parent of the input is a p element

Javascript

var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

CSS

div colorred

HTML

ltformgtltpgtltinput type=checkbox gtltpgtltformgt ltdivgtltdivgt

Example 4 Checks against an exist ing collect ion of alternat ing list elements Blue alternat inglist elements slide up while others turn red

Javascript

var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() var $li = $(this) i f ( $l i is( $alt ) ) $l i sl ideUp() else $l i css(background red) )

CSS

l i cursorpointer

HTML

ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

Example 5 An alternate way to achieve the above example using an element rather than ajQuery object Checks against an exist ing collect ion of alternat ing list elements Bluealternat ing list elements slide up while others turn red

Javascript

var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() i f ( $altis( this ) ) $(this)sl ideUp() else $(this)css(background red) )

CSS

l i cursorpointer

HTML

ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

eq

Reduce the set of matched elements to the one at the specif ied index

Added in version 14

eq(-index)jQuery

-indexInteger

An integer indicat ing the posit ion of the element count ing backwardsfrom the last element in the set

Given a jQuery object that represents a set of DOM elements the eq() method constructs anew jQuery object f rom one element within that set The supplied index ident if ies the posit ionof this element in the set

Consider a page with a simple list on it

ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltulgt

We can apply this method to the set of list items

$( l i )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-basedand refers to the posit ion of the element within the jQuery object not within the DOM tree

Providing a negat ive number indicates a posit ion start ing f rom the end of the set rather thanthe beginning For example

$( l i )eq(-2)css(background-color red)

This t ime list item 4 is turned red since it is two from the end of the set

If an element cannot be found at the specif ied zero-based index the method constructs a newjQuery object with an empty set and a length property of 0

$( l i )eq(5)css(background-color red)

Here none of the list items is turned red since eq(5) indicates the sixth of f ive list items

Example 1 Turn the div with index 2 blue by adding an appropriate class

Javascript

$(body)find(div)eq(2)addClass(blue)

CSS

div width60px height60px margin10px floatleft border2px solid blue blue backgroundblue

HTML

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

filter

Reduce the set of matched elements to those that match the selector or pass the funct ionstest

Added in version 14

f ilter(jQuery object)jQuery

jQueryobject Object

An exist ing jQuery object to match the current set of elementsagainst

Given a jQuery object that represents a set of DOM elements the f ilter() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is tested

new jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element all elements matching the selector will be included in the result

Consider a page with a simple list on it

list item 1

list item 2

list item 3

list item 4

list item 5

list item 6

We can apply this method to the set of list items

$( l i )fi lter( 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 even and odd use 0-based indexing)

Using a Filter Function

The second form of this method allows us to f ilter elements against a funct ion rather than aselector For each element if the funct ion returns t rue (or a t ruthy value) the element will beincluded in the f iltered set otherwise it will be excluded Suppose we have a somewhat moreinvolved HTML snippet

ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltligtlist item 6ltligtltulgt

We can select the list items then f ilter them based on their contents

$( l i )fi lter(function(index) return $(strong this)length == 1)css(background-color red)

This code will alter the f irst list item only as it contains exact ly one ltstronggt tag Within the

f ilter funct ion this refers to each DOM element in turn The parameter passed to the funct iontells us the index of that DOM element within the set matched by the jQuery object

We can also take advantage of the index passed through the funct ion which indicates the 0-based posit ion of the element within the unf iltered set of matched elements

$( l i )fi lter(function(index) return index 3 == 2)css(background-color red)

This alterat ion to the code will cause the third and sixth list items to be highlighted as it usesthe modulus operator () to select every item with an index value that when divided by 3 hasa remainder of 2

Example 1 Change the color of all divs then add a border to those with a middle class

Javascript

$(div)css(background c8ebcc) fi lter(middle) css(border-color red)

CSS

div width60px height60px margin5px floatleft border2px white solid

HTML

ltdivgtltdivgt

ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt

ltdivgtltdivgt

Example 2 Change the color of all divs then add a border to the second one (index == 1) andthe div with an id of fourth

Javascript

$(div)css(background b4b0da) fi lter(function (index) return index == 1 || $(this)attr( id) == fourth ) css(border 3px double red)

CSS

div width60px height60px margin5px floatleft border3px white solid

HTML

ltdiv id=firstgtltdivgt ltdiv id=secondgtltdivgt ltdiv id=thirdgtltdivgt

ltdiv id=fourthgtltdivgt ltdiv id=fifthgtltdivgt ltdiv id=sixthgtltdivgt

Example 3 Select all divs and f ilter the select ion with a DOM element keeping only the one withan id of unique

Javascript

$(div)fi lter( documentgetElementById(unique) )

Example 4 Select all divs and f ilter the select ion with a jQuery object keeping only the one withan id of unique

Javascript

$(div)fi lter( $(unique) )

Attributes

removeProp

Remove a property for the set of matched elements

Added in version 16

removeProp(propertyName)jQuery

propertyNameString The name of the property to set

The removeProp() method removes propert ies set by the prop() method

With some built -in propert ies of a DOM element or window object browsers may generate anerror if an at tempt is made to remove the property jQuery f irst assigns the value undef ined tothe property and ignores any error the browser generates In general it is only necessary toremove custom propert ies that have been set on an object and not built -in (nat ive) propert ies

Note Do not use this method to remove nat ive propert ies such as checked disabled orselected This will remove the property completely and once removed cannot be added againto element Use prop() to set these propert ies to false instead

Example 1 Set a numeric property on a paragraph and then remove it

Javascript

var $para = $(p)$paraprop(luggageCode 1234)$paraappend(The secret luggage code is String($paraprop(luggageCode)) )$pararemoveProp(luggageCode)$paraappend(Now the secret luggage code is String($paraprop(luggageCode)) )

CSS

img padding10px div colorred font-size24px

HTML

ltpgtltpgt

prop

Get the value of a property for the f irst element in the set of matched elements

Added in version 16

prop(propertyName)String

propertyNameString The name of the property to get

The prop() method gets the property value for only the first element in the matched set Itreturns undef ined for the value of a property that has not been set or if the matched set hasno elements To get the value for each element individually use a looping construct such asjQuerys each() or map() method

The dif ference between attributes and properties can be important in specif ic situat ions BeforejQuery 16 the at t r() method sometimes took property values into account when retrievingsome attributes which could cause inconsistent behavior As of jQuery 16 the prop() methodprovides a way to explicit ly retrieve property values while at t r() retrieves at t ributes

For example selectedIndex tagName nodeName nodeType ownerDocumentdefaultChecked and defaultSelected should be retrieved and set with the prop() method Priorto jQuery 16 these propert ies were retrievable with the at t r() method but this was not withinthe scope of at t r These do not have corresponding at t ributes and are only propert ies

Concerning boolean at t ributes consider a DOM element def ined by the HTML markup ltinputtype=checkbox checked=checked gt and assume it is in a JavaScript variable named elem

elemchecked t rue (Boolean) Will change with checkbox state

$(elem)prop(checked) t rue (Boolean) Will change with checkbox state

elemgetAttribute(checked)checked (String) Init ial state of the checkbox doesnot change

$(elem)attr(checked)(16)checked (String) Init ial state of the checkbox doesnot change

$(elem)attr(checked)(161+) checked (String) Will change with checkbox state

$(elem)attr(checked)(pre-16)

t rue (Boolean) Changed with checkbox state

According to the W3C forms specif icat ion the checked at t ribute is a boolean attribute whichmeans the corresponding property is t rue if the at t ribute is present at allacirceurordquoeven if for examplethe at t ribute has no value or an empty string value The preferred cross-browser-compat ibleway to determine if a checkbox is checked is to check for a t ruthy value on the element sproperty using one of the following

if ( elemchecked )

if ( $(elem)prop(checked) )

if ( $(elem)is(checked) )

If using jQuery 16 the code if ( $(elem)at t r(checked) ) will retrieve the actual content attributewhich does not change as the checkbox is checked and unchecked It is meant only to storethe default or init ial value of the checked property To maintain backwards compatability theat t r() method in jQuery 161+ will retrieve and update the property for you so no code forboolean at t ributes is required to be changed to prop() Nevertheless the preferred way toretrieve a checked value is with one of the opt ions listed above To see how this works in thelatest jQuery checkuncheck the checkbox in the example below

Example 1 Display the checked property and at t ribute of a checkbox as it changes

Javascript

$(input)change(function() var $input = $(this) $(p)html(attr(checked) ltbgt + $inputattr(checked) + ltbgtltbrgt + prop(checked) ltbgt + $inputprop(checked) + ltbgtltbrgt + is( checked) ltbgt + $inputis( checked) ) + ltbgt)change()

CSS

p margin 20px 0 0 b color blue

HTML

ltinput id=check1 type=checkbox checked=checkedgtltlabel for=check1gtCheck meltlabelgtltpgtltpgt

prop

Set one or more propert ies for the set of matched elements

Added in version 16

prop(propertyName funct ion(index oldPropertyValue))jQuery

propertyNameString The name of the property to set

funct ion(indexoldPropertyValue)Funct ion

A funct ion returning the value to set Receives the indexposit ion of the element in the set and the old propertyvalue as arguments Within the funct ion the keyword thisrefers to the current element

The prop() method is a convenient way to set the value of propert iesacirceurordquoespecially whensett ing mult iple propert ies using values returned by a funct ion or set t ing values on mult ipleelements at once It should be used when sett ing selectedIndex tagName nodeNamenodeType ownerDocument defaultChecked or defaultSelected Since jQuery 16 thesepropert ies can no longer be set with the at t r() method They do not have correspondingattributes and are only propert ies

Propert ies generally af fect the dynamic state of a DOM element without changing theserialized HTML attribute Examples include the value property of input elements the disabledproperty of inputs and buttons or the checked property of a checkbox The prop() methodshould be used to set disabled and checked instead of the at t r() method The val() methodshould be used for gett ing and sett ing value

$(input)prop(disabled false)$(input)prop(checked true)$(input)val(someValue)

Important the removeProp() method should not be used to set these propert ies to false Oncea nat ive property is removed it cannot be added again See removeProp() for moreinformat ion

Computed property values

By using a funct ion to set propert ies you can compute the value based on other propert ies ofthe element For example to toggle all checkboxes based of f their individual values

$(input[type=checkbox])prop(checked function( i val ) return val)

Note If nothing is returned in the setter funct ion (ie funct ion(index prop)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

Example 1 Disable all checkboxes on the page

Javascript

$(input[type=checkbox])prop( disabled true)

CSS

img padding10px div colorred font-size24px

HTML

ltinput type=checkbox checked=checked gt ltinput type=checkbox gt ltinput type=checkbox gt ltinput type=checkbox checked=checked gt

val

Get the current value of the f irst element in the set of matched elements

Added in version 10

val()String Number Array

The val() method is primarily used to get the values of form elements In the case of ltselectmult iple=mult iplegt elements the val() method returns an array containing each selectedopt ion

For selects and checkboxes you can also use the selected and checked selectors to get atvalues for example

$(selectfoo optionselected)val() get the value from a dropdown select$(selectfoo)val() get the value from a dropdown select even easier$( inputcheckboxchecked)val() get the value from a checked checkbox$( inputradio[name=bar]checked)val() get the value from a set of radio buttons

Example 1 Get the single value from a single select and an array of values from a mult ipleselect and display their values

Javascript

function displayVals() var singleValues = $(single)val() var multipleValues = $(multiple)val() || [] $(p)html(ltbgtSingleltbgt + singleValues + ltbgtMultipleltbgt + multipleValuesjoin( ))

$(select)change(displayVals) displayVals()

CSS

p colorred margin4px b colorblue

HTML

ltpgtltpgt ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

ltselectgt ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

ltoption selected=selectedgtMultiple3ltoptiongt ltselectgt

Example 2 Find the value of an input box

Javascript

$(input)keyup(function () var value = $(this)val() $(p)text(value) )keyup()

CSS

p colorblue margin8px

HTML

ltinput type=text value=some textgt ltpgtltpgt

val

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

Added in version 14

val(funct ion(index value))jQuery

funct ion(indexvalue)Funct ion

A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the old valueas arguments

This method is typically used to set the values of form f ields

Passing an array of element values allows matching ltinput type=checkboxgt ltinputtype=radiogt and ltopt iongts inside of n ltselect mult iple=mult iplegt to be selected In the caseof ltinput type=radiogts that are part of a radio group and ltselect mult iple=mult iplegt theother elements will be deselected

The val() method allows us to set the value by passing in a funct ion As of jQuery 14 thefunct ion is passed two arguments the current element s index and its current value

$( inputtextitems)val(function(index value) return value + + thisclassName)

This example appends the string items to the text inputs values

Example 1 Set the value of an input box

Javascript

$(button)cl ick(function () var text = $(this)text() $(input)val(text) )

CSS

button margin4px cursorpointer input margin4px colorblue

HTML

ltdivgt ltbuttongtFeedltbuttongt ltbuttongttheltbuttongt

ltbuttongtInputltbuttongt ltdivgt ltinput type=text value=click a button gt

Example 2 Use the funct ion argument to modify the value of an input box

Javascript

$( input)bind(blur function() $(this)val(function(i val) return valtoUpperCase() ) )

HTML

ltpgtType something and then click or tab out of the inputltpgt ltinput type=text value=type something gt

Example 3 Set a single select a mult iple select checkboxes and a radio button

Javascript

$(single)val(Single2) $(multiple)val([Multiple2 Multiple3]) $(input)val([check1check2 radio1 ])

CSS

body colorblue

HTML

ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=checkboxname value=check1gt check1 ltinput type=checkbox name=checkboxname value=check2gt check2 ltinput type=radio name=r value=radio1gt radio1 ltinput type=radio name=r value=radio2gt radio2

html

Get the HTML contents of the f irst element in the set of matched elements

Added in version 10

html()String

This method is not available on XML documents

In an HTML document html() can be used to get the contents of any element If the selectorexpression matches more than one element only the f irst match will have its HTML contentreturned Consider this code

$(divdemo-container)html()

In order for the following ltdivgts content to be retrieved it would have to be the f irst one withclass=demo-container in the document

ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

The result would look like this

ltdiv class=demo-boxgtDemonstration Boxltdivgt

This method uses the browsers innerHTML property Some browsers may not return HTML

that exact ly replicates the HTML source in an original document For example Internet Explorersometimes leaves of f the quotes around at t ribute values if they contain only alphanumericcharacters

Example 1 Click a paragraph to convert it f rom html to text

Javascript

$(p)cl ick(function () var htmlStr = $(this)html() $(this)text(htmlStr) )

CSS

p margin8px font-size20px colorblue cursorpointer b text-decorationunderline button cursorpointer

HTML

ltpgt

ltbgtClickltbgt to change the ltspan id=taggthtmlltspangt ltpgt ltpgt

to a ltspan id=textgttextltspangt node ltpgt ltpgt This ltbutton name=nadagtbuttonltbuttongt does nothing ltpgt

html

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

Added in version 14

html(funct ion(index oldhtml))jQuery

funct ion(indexoldhtml)Funct ion

A funct ion returning the HTML content to set Receives the indexposit ion of the element in the set and the old HTML value asarguments jQuery empt ies the element before calling the funct ionuse the oldhtml argument to reference the previous content Withinthe funct ion this refers to the current element in the set

The html() method is not available in XML documents

When html() is used to set an element s content any content that was in that element iscompletely replaced by the new content Consider the following HTML

ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

The content of ltdiv class=demo-containergt can be set like this

$(divdemo-container) html(ltpgtAll new content ltemgtYou betltemgtltpgt)

That line of code will replace everything inside ltdiv class=demo-containergt

ltdiv class=demo-containergt ltpgtAll new content ltemgtYou betltemgtltpgtltdivgt

As of jQuery 14 the html() method allows the HTML content to be set by passing in afunct ion

$(divdemo-container)html(function() var emph = ltemgt + $(p)length + paragraphsltemgt return ltpgtAll new content for + emph + ltpgt)

Given a document with six paragraphs this example will set the HTML of ltdiv class=demo-containergt to ltpgtAll new content for ltemgt6 paragraphsltemgtltpgt

This method uses the browsers innerHTML property Some browsers may not generate a DOMthat exact ly replicates the HTML source provided For example Internet Explorer prior toversion 8 will convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

Example 1 Add some html to each div

Javascript

$(div)html(ltspan class=redgtHello ltbgtAgainltbgtltspangt)

CSS

red colorred

HTML

ltspangtHelloltspangt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

Example 2 Add some html to each div then immediately do further manipulat ions to theinserted html

Javascript

$(div)html(ltbgtWowltbgt Such excitement) $(div b)append(documentcreateTextNode()) css(color red)

CSS

div colorblue font-size18px

HTML

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

toggleClass

Add or remove one or more classes from each element in the set of matched elementsdepending on either the classs presence or the value of the switch argument

Added in version 14

toggleClass(funct ion(index class switch) switch)jQuery

funct ion(indexclassswitch)Funct ion

A funct ion that returns class names to be toggled in the classattribute of each element in the matched set Receives the indexposit ion of the element in the set the old class value and the switchas arguments

switchBoolean (opt ional) A boolean value to determine whether the class should beadded or removed

This method takes one or more class names as its parameter In the f irst version if an elementin the matched set of elements already has the class then it is removed if an element does nothave the class then it is added For example we can apply toggleClass() to a simple ltdivgt

ltdiv class=tumblegtSome textltdivgt

The f irst t ime we apply $(divtumble)toggleClass(bounce) we get the following

ltdiv class=tumble bouncegtSome textltdivgt

The second t ime we apply $(divtumble)toggleClass(bounce) the ltdivgt class is returned tothe single tumble value

ltdiv class=tumblegtSome textltdivgt

Applying toggleClass(bounce spin) to the same ltdivgt alternates between ltdiv class=tumblebounce spingt and ltdiv class=tumblegt

The second version of toggleClass() uses the second parameter for determining whether theclass should be added or removed If this parameters value is t rue then the class is added iffalse the class is removed In essence the statement

$(foo)toggleClass(className addOrRemove)

is equivalent to

i f (addOrRemove) $(foo)addClass(className) else $(foo)removeClass(className)

As of jQuery 14 if no arguments are passed to toggleClass() all class names on the elementthe f irst t ime toggleClass() is called will be toggled Also as of jQuery 14 the class name to be

toggled can be determined by passing in a funct ion

$(divfoo)toggleClass(function() if ($(this)parent()is( bar)) return happy else return sad )

This example will toggle the happy class for ltdiv class=foogt elements if their parent elementhas a class of bar otherwise it will toggle the sad class

Example 1 Toggle the class highlight when a paragraph is clicked

Javascript

$(p)cl ick(function () $(this)toggleClass(highlight) )

CSS

p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundyellow

HTML

ltp class=bluegtClick to toggleltpgt ltp class=blue highlightgthighlightltpgt ltp class=bluegton theseltpgt ltp class=bluegtparagraphsltpgt

Example 2 Add the highlight class to the clicked paragraph on every third click of thatparagraph remove it every f irst and second click

Javascript

var count = 0$(p)each(function() var $thisParagraph = $(this) var count = 0 $thisParagraphclick(function() count++ $thisParagraphfind(span)text(cl icks + count) $thisParagraphtoggleClass(highlight count 3 == 0) ))

CSS

p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundred

HTML

ltp class=bluegtClick to toggle (ltspangtclicks 0ltspangt)ltpgt ltp class=blue highlightgthighlight (ltspangtclicks 0ltspangt)ltpgt ltp class=bluegton these (ltspangtclicks 0ltspangt)ltpgt

ltp class=bluegtparagraphs (ltspangtclicks 0ltspangt)ltpgt

Example 3 Toggle the class name(s) indicated on the buttons for each div

CSS

wrap gt div float left width 100px margin 1em 1em 0 0 padding=left 3px border 1px solid abc diva background-color aqua divb background-color burlywood divc background-color cornsilk

HTML

ltdiv class=buttonsgt ltbuttongttoggleltbuttongt ltbutton class=agttoggle altbuttongt ltbutton class=a bgttoggle a bltbuttongt ltbutton class=a b cgttoggle a b cltbuttongt lta href=gtresetltagtltdivgtltdiv class=wrapgt ltdivgtltdivgt ltdiv class=bgtltdivgt ltdiv class=a bgtltdivgt ltdiv class=a cgtltdivgtltdivgt

Javascript

var cls = [ a a b a b c]var divs = $(divwrap)children()var appendClass = function() divsappend(function() return ltdivgt + (thisclassName || none) + ltdivgt )

appendClass()

$(button)bind(cl ick function() var tc = thisclassName || undefined divstoggleClass(tc) appendClass())

$(a)bind(cl ick function(event) eventpreventDefault() divsempty()each(function(i) thisclassName = cls[i] ) appendClass())

removeClass

Remove a single class mult iple classes or all classes from each element in the set of matchedelements

Added in version 14

removeClass(funct ion(index class))jQuery

funct ion(index A funct ion returning one or more space-separated class names to be

class)Funct ion removed Receives the index posit ion of the element in the set and theold class value as arguments

If a class name is included as a parameter then only that class will be removed from the set ofmatched elements If no class names are specif ied in the parameter all classes will be removed

More than one class may be removed at a t ime separated by a space f rom the set of matchedelements like so

$(p)removeClass(myClass yourClass)

This method is of ten used with addClass() to switch elements classes from one to anotherlike so

$(p)removeClass(myClass noClass)addClass(yourClass)

Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

To replace all exist ing classes with another class we can use at t r(class newClass) instead

As of jQuery 14 the removeClass() method allows us to indicate the class to be removed bypassing in a funct ion

$( l i last)removeClass(function() return $(this)prev()attr(class) )

This example removes the class name of the penult imate ltligt f rom the last ltligt

Example 1 Remove the class blue f rom the matched elements

Javascript

$(peven)removeClass(blue)

CSS

p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

HTML

ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

ltp class=blue undergtGoodbyeltpgt

Example 2 Remove the class blue and under f rom the matched elements

Javascript

$(podd)removeClass(blue under)

CSS

p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

HTML

ltp class=blue undergtHelloltpgt

ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt ltp class=blue undergtGoodbyeltpgt

Example 3 Remove all the classes from the matched elements

Javascript

$(peq(1))removeClass()

CSS

p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

HTML

ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

ltp class=blue undergtGoodbyeltpgt

hasClass

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

Added in version 12

hasClass(className)Boolean

classNameString The class name to search for

Elements may have more than one class assigned to them In HTML this is represented byseparat ing the class names with a space

ltdiv id=mydiv class=foo bargtltdivgt

The hasClass() method will return t rue if the class is assigned to an element even if otherclasses also are For example given the HTML above the following will return t rue

$(mydiv)hasClass(foo)

As would

$(mydiv)hasClass(bar)

While this would return false

$(mydiv)hasClass(quux)

Example 1 Looks for the paragraph that contains selected as a class

Javascript

$(divresult1)append($(pfirst)hasClass(selected)toString())$(divresult2)append($(plast)hasClass(selected)toString())$(divresult3)append($(p)hasClass(selected)toString())

CSS

p margin 8px font-size16px selected colorred

HTML

ltpgtThis paragraph is black and is the first paragraphltpgt ltp class=selectedgtThis paragraph is red and is the second paragraphltpgt

ltdiv id=result1gtFirst paragraph has selected class ltdivgt ltdiv id=result2gtSecond paragraph has selected class ltdivgt ltdiv id=result3gtAt least one paragraph has selected class ltdivgt

removeAttr

Remove an at t ribute f rom each element in the set of matched elements

Added in version 10

removeAttr(at t ributeName)jQuery

attributeNameString An at t ribute to remove

The removeAttr() method uses the JavaScript removeAttribute() funct ion but it has theadvantage of being able to be called direct ly on a jQuery object and it accounts for dif ferentat t ribute naming across browsers

NoteIf at tempt ing to remove an inline onclick event handler using removeAttr() one may f indthat this doesnt achieve the desired ef fect in Internet Explorer 67 or 8 Instead it isrecommended to opt for using prop() to achieve this as follows

$elementprop(onclick null)consolelog(onclick property $element[0]onclick)

We may update the behavior of removeAttr() at some point in the future to better handle thishowever for the t ime being the above should be considered the standard cross-browserapproach to this problem

Example 1 Clicking the button enables the input next to it

Javascript

$(button)cl ick(function () $(this)next()removeAttr(disabled) focus() val(editable now))

HTML

ltbuttongtEnableltbuttongtltinput type=text disabled=disabled value=cant edit this gt

attr

Get the value of an at t ribute for the f irst element in the set of matched elements

Added in version 10

attr(at t ributeName)String

attributeNameString The name of the at t ribute to get

The at t r() method gets the at t ribute value for only the first element in the matched set To getthe value for each element individually use a looping construct such as jQuerys each() ormap() method

As of jQuery 16 the at t r() method returns undef ined for at t ributes that have not been set Inaddit ion at t r() should not be used on plain objects arrays the window or the document Toretrieve and change DOM propert ies use the prop() method

Using jQuerys at t r() method to get the value of an element s at t ribute has two main benef its

1 Convenience It can be called direct ly on a jQuery object and chained to other jQuerymethods

2 Cross-browser consistency The values of some attributes are reported inconsistent lyacross browsers and even across versions of a single browser The at t r() methodreduces such inconsistencies

Note Attribute values are strings with the exception of a few attributes such asvalue and tabindex

Example 1 Find the t it le at t ribute of the f irst in the page

Javascript

var title = $(em)attr(title) $(div)text(title)

CSS

em colorblue font-weightbold div colorred

HTML

ltpgt Once there was a ltem title=huge giganticgtlargeltemgt dinosaurltpgt

The title of the emphasis isltdivgtltdivgt

attr

Set one or more at t ributes for the set of matched elements

Added in version 11

attr(at t ributeName funct ion(index at t r))jQuery

attributeNameString The name of the at t ribute to set

funct ion(indexat t r)Funct ion

A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the oldattribute value as arguments

The at t r() method is a convenient way to set the value of at t ributesacirceurordquoespecially when sett ingmult iple at t ributes or using values returned by a funct ion Consider the following image

ltimg id=greatphoto src=brush-sellerjpg alt=brush seller gt

Setting a simple attribute

To change the alt at t ribute simply pass the name of the at t ribute and its new value to theat t r() method

$(greatphoto)attr(alt Beij ing Brush Seller)

Add an at t ribute the same way

$(greatphoto)attr(title Photo by Kelly Clark)

Setting several attributes at once

To change the alt at t ribute and add the t it le at t ribute at the same t ime pass both sets ofnames and values into the method at once using a map (JavaScript object literal) Each key-value pair in the map adds or modif ies an at t ribute

$(greatphoto)attr( alt Beij ing Brush Seller title photo by Kelly Clark)

When sett ing mult iple at t ributes the quotes around at t ribute names are opt ional

WARNING When sett ing the class at t ribute you must always use quotes

Note jQuery prohibits changing the type at t ribute on an ltinputgt or ltbuttongt element and willthrow an error in all browsers This is because the type at t ribute cannot be changed in InternetExplorer

Computed attribute values

By using a funct ion to set at t ributes you can compute the value based on other propert ies ofthe element For example to concatenate a new value with an exist ing value

$(greatphoto)attr(title function(i val) return val + - photo by Kelly Clark)

This use of a funct ion to compute at t ribute values can be part icularly useful when modifyingthe at t ributes of mult iple elements at once

Note If nothing is returned in the setter funct ion (ie funct ion(index at t r)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

Example 1 Set some attributes for all s in the page

Javascript

$(img)attr( src imageshatgif title jQuery alt jQuery Logo)$(div)text($(img)attr(alt))

CSS

img padding10px div colorred font-size24px

HTML

ltimg gt ltimg gt ltimg gt

ltdivgtltBgtAttribute of AjaxltBgtltdivgt

Example 2 Disable buttons greater than the 1st button

Javascript

$(buttongt(1))attr(disableddisabled)

CSS

button margin10px

HTML

ltbuttongt0th Buttonltbuttongt ltbuttongt1st Buttonltbuttongt ltbuttongt2nd Buttonltbuttongt

Example 3 Set the id for divs based on the posit ion in the page

Javascript

$(div)attr( id function (arr) return div-id + arr)each(function () $(span this)html((ID = ltbgt + thisid + ltbgt)))

CSS

div colorblue span colorred b font-weightbolder

HTML

ltdivgtZero-th ltspangtltspangtltdivgt ltdivgtFirst ltspangtltspangtltdivgt ltdivgtSecond ltspangtltspangtltdivgt

Example 4 Set the src at t ribute f rom t it le at t ribute on the image

Javascript

$(img)attr(src function() return images + thistitle )

HTML

ltimg title=hatgifgt

addClass

Adds the specif ied class(es) to each of the set of matched elements

Added in version 14

addClass(funct ion(index currentClass))jQuery

funct ion(indexcurrentClass)Funct ion

A funct ion returning one or more space-separated class namesto be added to the exist ing class name(s) Receives the indexposit ion of the element in the set and the exist ing class name(s)as arguments Within the funct ion this refers to the currentelement in the set

It s important to note that this method does not replace a class It simply adds the classappending it to any which may already be assigned to the elements

More than one class may be added at a t ime separated by a space to the set of matchedelements like so

$(p)addClass(myClass yourClass)

This method is of ten used with removeClass() to switch elements classes from one toanother like so

$(p)removeClass(myClass noClass)addClass(yourClass)

Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

As of jQuery 14 the addClass() methods argument can receive a funct ion

$(ul l i last)addClass(function() return item- + $(this)index())

Given an unordered list with f ive ltligt elements this example adds the class item-4 to the lastltligt

Example 1 Adds the class selected to the matched elements

Javascript

$(plast)addClass(selected)

CSS

p margin 8px font-size16px selected colorblue highlight backgroundyellow

HTML

ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

Example 2 Adds the classes selected and highlight to the matched elements

Javascript

$(plast)addClass(selected highlight)

CSS

p margin 8px font-size16px selected colorred highlight backgroundyellow

HTML

ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

Example 3 Pass in a funct ion to addClass() to add the green class to a div that already has ared class

Javascript

$(div)addClass(function(index currentClass) var addedClass

i f ( currentClass === red ) addedClass = green $(p)text(There is one green div) return addedClass )

CSS

div background white red background red redgreen background green

HTML

ltdivgtThis div should be whiteltdivgt ltdiv class=redgtThis div wil l be green because it now has the green and red classes It would be red if the addClass function failedltdivgt ltdivgtThis div should be whiteltdivgt ltpgtThere are zero green divsltpgt

CSS

jQuerycssHooks

Hook direct ly into jQuery to override how part icular CSS propert ies are retrieved or set normalize CSS property naming or create custom propert ies

Added in version 143

The $cssHooks object provides a way to def ine funct ions for gett ing and sett ing part icularCSS values It can also be used to create new cssHooks for normalizing CSS3 features such asbox shadows and gradients

For example some versions of Webkit -based browsers require -webkit -border-radius to set theborder-radius on an element while earlier Firefox versions require -moz-border-radius AcssHook can normalize these vendor-pref ixed propert ies to let css() accept a single standardproperty name (border-radius or with DOM property syntax borderRadius)

In addit ion to providing f ine-grained control over how specif ic style propert ies are handled$cssHooks also extends the set of propert ies available to the animate() method

Def ining a new cssHook is straight-forward The skeleton template below can serve as a guideto creat ing your own

(function($) first check to see if cssHooks are supported if ( $cssHooks ) i f not output an error message throw(jQuery 143 or above is required for this plugin to work) return

$cssHooks[someCSSProp] = get function( elem computed extra ) handle getting the CSS property set function( elem value ) handle setting the CSS value )(jQuery)

Feature Testing

Before normalizing a vendor-specif ic CSS property f irst determine whether the browsersupports the standard property or a vendor-pref ixed variat ion For example to check forsupport of the border-radius property see if any variat ion is a member of a temporary

element s style object

(function($) function styleSupport( prop ) var vendorProp supportedProp

capitalize first character of the prop to test vendor prefix capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

i f ( prop in divstyle )

browser supports standard CSS property name supportedProp = prop else

otherwise test support for vendor-prefixed property names for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

avoid memory leak in IE div = null add property to $support so it can be accessed elsewhere $support[ prop ] = supportedProp return supportedProp

call the function eg testing for border-radius support styleSupport( borderRadius ))(jQuery)

Defining a complete cssHook

To def ine a complete cssHook combine the support test with a f illed-out version of theskeleton template provided in the f irst example

(function($) if ( $cssHooks ) throw(jQuery 143+ is needed for this plugin to work) return function styleSupport( prop ) var vendorProp supportedProp capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

i f ( prop in divstyle ) supportedProp = prop else for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

div = null $support[ prop ] = supportedProp return supportedProp

var borderRadius = styleSupport( borderRadius )

Set cssHooks only for browsers that support a vendor-prefixed border radius if ( borderRadius ampamp borderRadius == borderRadius ) $cssHookborderRadius = get function( elem computed extra ) return $css( elem borderRadius ) set function( elem value) elemstyle[ borderRadius ] = value )(jQuery)

You can then set the border radius in a supported browser using either the DOM (camelCased)style or the CSS (hyphenated) style

$(element)css(borderRadius 10px)$(another)css(border-radius 20px)

If the browser lacks support for any form of the CSS property vendor-pref ixed or not the styleis not applied to the element However if the browser supports a proprietary alternat ive it canbe applied to the cssHooks instead

(function($) feature test for support of a CSS property and a proprietary alternative

i f ( $supportsomeCSSProp ampamp $supportsomeCSSProp == someCSSProp )

Set cssHooks for browsers that support only a vendor-prefixed someCSSProp $cssHooksomeCSSProp = get function( elem computed extra ) return $css( elem $supportsomeCSSProp ) set function( elem value) elemstyle[ $supportsomeCSSProp ] = value else if ( supportsProprietaryAlternative ) $cssHooksomeCSSProp = get function( elem computed extra ) Handle crazy conversion from the proprietary alternative set function( elem value ) Handle crazy conversion to the proprietary alternative

)(jQuery)

Special units

By default jQuery adds a px unit to the values passed to the css() method This behavior canbe prevented by adding the property to the jQuerycssNumber object

$cssNumber[someCSSProp] = true

Animating with cssHooks

A cssHook can also hook into jQuerys animat ion mechanism by adding a property to thejQueryfxstep object

$fxstep[someCSSProp] = function(fx) $cssHooks[someCSSProp]set( fxelem fxnow + fxunit )

Note that this works best for simple numeric-value animat ions More custom code may berequired depending on the CSS property the type of value it returns and the animat ionscomplexity

outerWidth

Get the current computed width for the f irst element in the set of matched elements includingpadding and border

Added in version 126

outerWidth(includeMargin)Integer

includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

Returns the width of the element along with lef t and right padding border and opt ionallymargin in pixels

If includeMargin is omit ted or false the padding and border are included in the calculat ion ift rue the margin is also included

This method is not applicable to window and document objects for these use width() instead

Example 1 Get the outerWidth of a paragraph

Javascript

var p = $(pfirst)$(plast)text( outerWidth + pouterWidth()+ outerWidth(true) + pouterWidth(true) )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

outerHeight

Get the current computed height for the f irst element in the set of matched elements includingpadding border and opt ionally margin

Added in version 126

outerHeight(includeMargin)Integer

includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

The top and bottom padding and border are always included in the outerHeight() calculat ion ifthe includeMargin argument is set to t rue the margin (top and bottom) is also included

This method is not applicable to window and document objects for these use height() instead

Example 1 Get the outerHeight of aparagraph

Javascript

var p = $(pfirst)$(plast)text( outerHeight + pouterHeight() + outerHeight(true) + pouterHeight(true) )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

innerWidth

Get the current computed width for the f irst element in the set of matched elements includingpadding but not border

Added in version 126

innerWidth()Integer

This method returns the width of the element including lef t and right padding in pixels

This method is not applicable to window and document objects for these use width() instead

Example 1 Get the innerWidth of a paragraph

Javascript

var p = $(pfirst)$(plast)text( innerWidth + pinnerWidth() )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

innerHeight

Get the current computed height for the f irst element in the set of matched elements includingpadding but not border

Added in version 126

innerHeight()Integer

This method returns the height of the element including top and bottom padding in pixels

This method is not applicable to window and document objects for these use height() instead

Example 1 Get the innerHeight of aparagraph

Javascript

var p = $(pfirst)$(plast)text( innerHeight + pinnerHeight() )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

width

Get the current computed width for the f irst element in the set of matched elements

Added in version 10

width()Integer

The dif ference between css(width) and width() is that the lat ter returns a unit -less pixel value(for example 400) while the former returns a value with units intact (for example 400px) Thewidth() method is recommended when an element s width needs to be used in a mathematicalcalculat ion

This method is also able to f ind the width of thewindow and document

$(window)width() returns width of browser viewport$(document)width() returns width of HTML document

Note that width() will always return the content width regardless of the value of the CSS box-sizing property

Example 1 Show various widths Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

Javascript

function showWidth(ele w) $(div)text(The width for the + ele + is + w + px) $(getp)cl ick(function () showWidth(paragraph $(p)width()) ) $(getd)cl ick(function () showWidth(document $(document)width()) ) $(getw)cl ick(function () showWidth(window $(window)width()) )

CSS

body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

HTML

ltbutton id=getpgtGet Paragraph Widthltbuttongt ltbutton id=getdgtGet Document Widthltbuttongt ltbutton id=getwgtGet Window Widthltbuttongt

ltdivgtampnbspltdivgt ltpgt Sample paragraph to test width ltpgt

width

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

Added in version 141

width(funct ion(index width))jQuery

funct ion(indexwidth)Funct ion

A funct ion returning the width to set Receives the index posit ion ofthe element in the set and the old width as arguments Within thefunct ion this refers to the current element in the set

When calling width(value) the value can be either a string (number and unit ) or a number Ifonly 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 100px 50 or auto)Note that in modern browsers the CSS width property does not include padding border ormargin unless the box-sizing CSS property is used

If no explicit unit was specif ied (like em or ) then px is concatenated to the value

Note that width(value) sets the width of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterWidth of the box instead of the content width

Example 1 To set the width of each div on click to 30px plus a color change

Javascript

$(div)one(cl ick function () $(this)width(30) css(cursorauto background-colorblue) )

CSS

div width70px height50px floatleft margin5px backgroundred cursorpointer

HTML

ltdivgtltdivgt ltdivgtdltdivgt

ltdivgtdltdivgt ltdivgtdltdivgt ltdivgtdltdivgt

height

Get the current computed height for the f irst element in the set of matched elements

Added in version 10

height()Integer

The dif ference between css(height ) and height() is that the lat ter returns a unit -less pixelvalue (for example 400) while the former returns a value with units intact (for example 400px)The height() method is recommended when an element s height needs to be used in amathematical calculat ion

This method is also able to f ind the heightof the window and document

$(window)height() returns height of browser viewport$(document)height() returns height of HTML document

Note that height() will always return the content height regardless of the value of the CSSbox-sizing property

Example 1 Show various heights Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

Javascript

function showHeight(ele h) $(div)text(The height for the + ele + is + h + px) $(getp)cl ick(function () showHeight(paragraph $(p)height()) ) $(getd)cl ick(function () showHeight(document $(document)height()) ) $(getw)cl ick(function () showHeight(window $(window)height()) )

CSS

body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

HTML

ltbutton id=getpgtGet Paragraph Heightltbuttongt ltbutton id=getdgtGet Document Heightltbuttongt ltbutton id=getwgtGet Window Heightltbuttongt

ltdivgtampnbspltdivgt ltpgt Sample paragraph to test height ltpgt

height

Set the CSS height of every matched element

Added in version 141

height(funct ion(index height))jQuery

funct ion(indexheight)Funct ion

A funct ion returning the height to set Receives the index posit ion ofthe element in the set and the old height as arguments Within thefunct ion this refers to the current element in the set

When calling height(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is providedhowever a valid CSS measurement must be provided for the height (such as 100px 50 orauto) Note that in modern browsers the CSS height property does not include paddingborder or margin

If no explicit unit was specif ied (like em or ) then px is concatenated to the value

Note that height(value) sets the height of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterHeight of the box instead of the content height

Example 1 To set the height of each div on click to 30px plus a color change

Javascript

$(div)one(cl ick function () $(this)height(30) css(cursorauto backgroundColorgreen) )

CSS

div width50px height70px floatleft margin5px backgroundrgb(2551400) cursorpointer

HTML

ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

scrollLeft

Get the current horizontal posit ion of the scroll bar for the f irst element in the set of matchedelements

Added in version 126

scrollLef t ()Integer

The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area If the scroll bar is at the very lef t or if the element is not scrollablethis number will be 0

Example 1 Get the scrollLef t of a paragraph

Javascript

var p = $(pfirst) $(plast)text( scrollLeft + pscrollLeft() )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

scrollLeft

Set the current horizontal posit ion of the scroll bar for each of the set of matched elements

Added in version 126

scrollLef t (value)jQuery

valueNumber An integer indicat ing the new posit ion to set the scroll bar to

The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area Sett ing the scrollLef t posit ions the horizontal scroll of each matchedelement

Example 1 Set the scrollLef t of a div

Javascript

$(divdemo)scrollLeft(300)

CSS

divdemo backgroundCCCCCC none repeat scroll 0 0 border3px solid 666666 margin5px padding5px positionrelative width200px height100px overflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

HTML

ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

scrollTop

Get the current vert ical posit ion of the scroll bar for the f irst element in the set of matchedelements

Added in version 126

scrollTop()Integer

The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area If the scroll bar is at the very top or if the element is not scrollable thisnumber will be 0

Example 1 Get the scrollTop of a paragraph

Javascript

var p = $(pfirst)$(plast)text( scrollTop + pscrollTop() )

CSS

p margin10pxpadding5pxborder2px solid 666

HTML

ltpgtHelloltpgtltpgtltpgt

scrollTop

Set the current vert ical posit ion of the scroll bar for each of the set of matched elements

Added in version 126

scrollTop(value)jQuery

valueNumber An integer indicat ing the new posit ion to set the scroll bar to

The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area Sett ing the scrollTop posit ions the vert ical scroll of each matched element

Example 1 Set the scrollTop of a div

Javascript

$(divdemo)scrollTop(300)

CSS

divdemo backgroundCCCCCC none repeat scroll 0 0border3px solid 666666margin5pxpadding5pxpositionrelativewidth200pxheight100pxoverflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

HTML

ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

position

Get the current coordinates of the f irst element in the set of matched elements relat ive to theoffset parent

Added in version 12

posit ion()Object

The posit ion() method allows us to retrieve the current posit ion of an element relative to theoffset parent Contrast this with of fset() which retrieves the current posit ion relative to thedocument When posit ioning a new element near another one and within the same containingDOM element posit ion() is the more useful

Returns an object containing the propert ies top and lef t

Example 1 Access the posit ion of the second paragraph

Javascript

var p = $(pfirst)var position = pposition()$(plast)text( left + positionleft + top + positiontop )

CSS

div padding 15px p margin-left10px

HTML

ltdivgt ltpgtHelloltpgtltdivgtltpgtltpgt

offset

Get the current coordinates of the f irst element in the set of matched elements relat ive to thedocument

Added in version 12

offset()Object

The of fset() method allows us to retrieve the current posit ion of an element relative to thedocument Contrast this with posit ion() which retrieves the current posit ion relative to the offsetparent When posit ioning a new element on top of an exist ing one for global manipulat ion (inpart icular for implement ing drag-and-drop) of fset() is the more useful

of fset() returns an object containing the propert ies top and lef t

Note jQuery does not support getting the offset coordinates of hidden elements oraccounting for borders margins or padding set on the body element

Example 1 Access the of fset of the second paragraph

Javascript

var p = $(plast)var offset = poffset()phtml( left + offsetleft + top + offsettop )

CSS

p margin-left10px

HTML

ltpgtHelloltpgtltpgt2nd Paragraphltpgt

Example 2 Click to see the of fset

Javascript

$( documentbody)cl ick(function (e) var offset = $(this)offset() estopPropagation() $(result)text(thistagName + coords ( + offsetleft + + offsettop + )))

CSS

p margin-left10px colorblue width200px cursorpointer span colorred cursorpointer divabs width50px height50px positionabsolute left220px top35px background-colorgreen cursorpointer

HTML

ltdiv id=resultgtClick an elementltdivgtltpgt This is the best way to ltspangtfindltspangt an offsetltpgt

ltdiv class=absgtltdivgt

offset

Set the current coordinates of every element in the set of matched elements relat ive to thedocument

Added in version 14

offset(funct ion(index coords))jQuery

funct ion(indexcoords)Funct ion

A funct ion to return the coordinates to set Receives the index of theelement in the collect ion as the f irst argument and the currentcoordinates as the second argument The funct ion should return anobject with the new top and lef t propert ies

The of fset() set ter method allows us to reposit ion an element The element s posit ion isspecif ied relative to the document If the element s posit ion style property is current ly stat ic it

will be set to relat ive to allow for this reposit ioning

Example 1 Set the of fset of the second paragraph

Javascript

$(plast)offset( top 10 left 30 )

CSS

p margin-left10px

HTML

ltpgtHelloltpgtltpgt2nd Paragraphltpgt

css

Get the value of a style property for the f irst element in the set of matched elements

Added in version 10

css(propertyName)String

propertyNameString A CSS property

The css() method is a convenient way to get a style property f rom the f irst matched elementespecially in light of the dif ferent ways browsers access most of those propert ies (thegetComputedStyle() method in standards-based browsers versus the currentStyle andrunt imeStyle propert ies in Internet Explorer) and the dif ferent terms browsers use for certainpropert ies For example Internet Explorers DOM implementat ion refers to the f loat property asstyleFloat while W3C standards-compliant browsers refer to it as cssFloat The css() methodaccounts for such dif ferences producing the same result no matter which term we use Forexample an element that is f loated lef t will return the string lef t for each of the following threelines

1 $(divlef t )css(f loat )

2 $(divlef t )css(cssFloat )

3 $(divlef t )css(styleFloat )

Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color)and css(backgroundColor) Dif ferent browsers may return CSS color values that are logicallybut not textually equal eg FFF f f f f f f and rgb(255255255)

but not textually equal eg FFF f f f f f f and rgb(255255255)

Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

Example 1 To access the background color of a clicked div

Javascript

$(div)cl ick(function () var color = $(this)css(background-color) $(result)html(That div is ltspan style=color + color + gt + color + ltspangt))

CSS

div width60px height60px margin5px floatleft

HTML

ltspan id=resultgtampnbspltspangtltdiv style=background-colorbluegtltdivgtltdiv style=background-colorrgb(159930)gtltdivgt

ltdiv style=background-color123456gtltdivgtltdiv style=background-colorf11gtltdivgt

css

Set one or more CSS propert ies for the set of matched elements

Added in version 10

css(map)jQuery

mapMap A map of property-value pairs to set

As with the prop() method the css() method makes sett ing propert ies of elements quick andeasy This method can take either a property name and value as separate parameters or asingle map of key-value pairs (JavaScript object notat ion)

Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color

f fe border-lef t 5px solid ccc) and css(backgroundColor f fe borderLeft 5px solidccc) Not ice that with the DOM notat ion quotat ion marks around the property names areopt ional but with CSS notat ion theyre required due to the hyphen in the name

When using css() as a setter jQuery modif ies the element s style property For example$(mydiv)css(color green) is equivalent to documentgetElementById(mydiv)stylecolor =green Sett ing the value of a style property to an empty string acirceurordquo eg $(mydiv)css(color )acirceurordquo removes that property f rom an element if it has already been direct ly applied whether in theHTML style at t ribute through jQuerys css() method or through direct DOM manipulat ion ofthe style property It does not however remove a style that has been applied with a CSS rule ina stylesheet or ltstylegt element

As of jQuery 16 css() accepts relat ive values similar to animate() Relat ive values are a stringstart ing with += or -= to increment or decrement the current value For example if an element spadding-lef t was 10px css( padding-lef t +=15 ) would result in a total padding-lef t of 25px

As of jQuery 14 css() allows us to pass a funct ion as the property value

$(divexample)css(width function(index) return index 50)

This example sets the widths of the matched elements to incrementally larger values

Note If nothing is returned in the setter funct ion (ie funct ion(index style)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

Example 1 To change the color of any paragraph to red on mouseover event

Javascript

$(p)mouseover(function () $(this)css(colorred) )

CSS

p colorblue width200px font-size14px

HTML

ltpgtJust roll the mouse over meltpgt

ltpgtOr me to see a color changeltpgt

Example 2 Increase the width of box by 200 pixels

Javascript

$(box)one( cl ick function () $( this )css( width+=200 ) )

CSS

box background black color snow width100px padding10px

HTML

ltdiv id=boxgtClick me to growltdivgt

Example 3 To highlight a clicked word in the paragraph

Javascript

var words = $(pfirst)text()split( ) var text = wordsjoin(ltspangt ltspangt) $(pfirst)html(ltspangt + text + ltspangt) $(span)cl ick(function () $(this)css(background-coloryellow) )

CSS

p colorblue font-weightbold cursorpointer

HTML

ltpgt Once upon a time there was a man who l ived in a pizza parlor This man just loved pizza and ate it al l the time He went on to be the happiest man in the world The endltpgt

Example 4 To set the color of all paragraphs to red and background to blue

Javascript

$(p)hover(function () $(this)css(background-color yellow font-weight bolder) function () var cssObj = background-color ddd font-weight color rgb(040244) $(this)css(cssObj) )

CSS

p colorgreen

HTML

ltpgtMove the mouse over a paragraphltpgt ltpgtLike this one or the one aboveltpgt

Example 5 Increase the size of a div when you click it

Javascript

$(div)cl ick(function() $(this)css( width function(index value) return parseFloat(value) 12 height function(index value) return parseFloat(value) 12

) )

CSS

div width 20px height 15px background-color f33

HTML

ltdivgtclickltdivgt ltdivgtclickltdivgt

toggleClass see Attributes

removeClass see Attributes

hasClass see Attributes

addClass see Attributes

Manipulation

removeProp see Attributes

prop see Attributes

prop see Attributes

outerWidth see CSS

outerHeight see CSS

innerWidth see CSS

innerHeight see CSS

width see CSS

width see CSS

height see CSS

height see CSS

scrollLeft see CSS

scrollLeft see CSS

scrollTop see CSS

scrollTop see CSS

position see CSS

offset see CSS

offset see CSS

css see CSS

css see CSS

unwrap

Remove the parents of the set of matched elements f rom the DOM leaving the matchedelements in their place

Added in version 14

unwrap()jQuery

The unwrap() method removes the element s parent This is ef fect ively the inverse of thewrap() method The matched elements (and their siblings if any) replace their parents withinthe DOM structure

Example 1 Wrapunwrap a div around each of the paragraphs

Javascript

$(button)toggle(function() $(p)wrap(ltdivgtltdivgt) function() $(p)unwrap())

CSS

div border 2px solid blue p backgroundyellow margin4px

HTML

ltbuttongtwrapunwrapltbuttongtltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

detach

Remove the set of matched elements f rom the DOM

Added in version 14

detach(selector)jQuery

selectorSelector (opt ional) A selector expression that f ilters the set of matchedelements to be removed

The detach() method is the same as remove() except that detach() keeps all jQuery dataassociated with the removed elements This method is useful when removed elements are tobe reinserted into the DOM at a later t ime

Example 1 Detach all paragraphs from the DOM

Javascript

$(p)cl ick(function() $(this)toggleClass(off) ) var p $(button)cl ick(function() i f ( p ) pappendTo(body) p = null else p = $(p)detach() )

CSS

p backgroundyellow margin6px 0 poff background black

HTML

ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtAttachdetach paragraphsltbuttongt

clone

Create a deep copy of the set of matched elements

Added in version 15

clone(withDataAndEvents deepWithDataAndEvents)jQuery

withDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data should be copied along with the

elements The default value is false In jQuery 150the default value was incorrectly true it was changedback to false in 151 and up

deepWithDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data for all children of the clonedelement should be copied By default its valuematches the f irst argument s value (which defaultsto false)

The clone() method performs a deep copy of the set of matched elements meaning that itcopies the matched elements as well as all of their descendant elements and text nodes Whenused in conjunct ion with one of the insert ion methods clone() is a convenient way to duplicateelements on a page Consider the following HTML

ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

As shown in the discussion for append() normally when an element is inserted somewhere inthe DOM it is moved from its old locat ion So given the code

$(hello)appendTo(goodbye)

The result ing DOM structure would be

ltdiv class=containergt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

To prevent this and instead create a copy of the element you could write the following

$(hello)clone()appendTo(goodbye)

This would produce

ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

Note that when using the clone() method you can modify the cloned elements ortheir contents before (re-)inserting them into the document

Normally any event handlers bound to the original element are not copied to the clone Theopt ional withDataAndEvents parameter allows us to change this behavior and to instead makecopies of all of the event handlers as well bound to the new copy of the element As of jQuery14 all element data (at tached by the data() method) is also copied to the new copy

However objects and arrays within element data are not copied and will cont inue to be sharedbetween the cloned element and the original element To deep copy all data copy each onemanually

var $elem = $(elem)data( arr [ 1 ] ) Original element with attached data $clone = $elemclone( true ) data( arr $extend( [] $elemdata(arr) ) ) Deep copy to prevent data sharing

As of jQuery 15 withDataAndEvents can be opt ionally enhanced withdeepWithDataAndEvents to copy the events and data for all children of the cloned element

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

Javascript

$(b)clone()prependTo(p)

HTML

ltbgtHelloltbgtltpgt how are youltpgt

Example 2 When using clone() to clone a collect ion of elements that are not at tached to theDOM their order when inserted into the DOM is not guaranteed However it may be possible topreserve sort order with a workaround as demonstrated

CSS

orig copy copy-correct float left width 20

Javascript

sort order is not guaranteed here and may vary with browser $(copy)append($(orig elem) clone() children(a) prepend(foo - ) parent() clone()) correct way to approach where order is maintained$(copy-correct) append($(orig elem) clone() children(a) prepend(bar - ) end())

HTML

ltdiv id=origgt ltdiv class=elemgtltagt1ltagtltdivgt ltdiv class=elemgtltagt2ltagtltdivgt ltdiv class=elemgtltagt3ltagtltdivgt ltdiv class=elemgtltagt4ltagtltdivgt ltdiv class=elemgtltagt5ltagtltdivgtltdivgtltdiv id=copygtltdivgtltdiv id=copy-correctgtltdivgt

remove

Remove the set of matched elements f rom the DOM

Added in version 10

remove(selector)jQuery

selectorString (opt ional) A selector expression that f ilters the set of matchedelements to be removed

Similar to empty() the remove() method takes elements out of the DOM Use remove() when

you want to remove the element itself as well as everything inside it In addit ion to theelements themselves all bound events and jQuery data associated with the elements areremoved To remove the elements without removing data and events use detach() instead

Consider the following HTML

ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

We can target any element for removal

$(hello)remove()

This will result in a DOM structure with the ltdivgt element deleted

ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo Other jQuery constructs such as data or event handlers are erased as well

We can also include a selector as an opt ional parameter For example we could rewrite theprevious DOM removal code as follows

$(div)remove(hello)

This would result in the same DOM structure

ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

Example 1 Removes all paragraphs from the DOM

Javascript

$(button)cl ick(function () $(p)remove() )

CSS

p backgroundyellow margin6px 0

HTML

ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtCall remove() on paragraphsltbuttongt

Example 2 Removes all paragraphs that contain Hello f rom the DOM Analogous to doing$(p)f ilter(contains(Hello))remove()

Javascript

$(button)cl ick(function () $(p)remove(contains(Hello)) )

CSS

p backgroundyellow margin6px 0

HTML

ltp class=hellogtHelloltpgt how are ltpgtyoultpgt

ltbuttongtCall remove(contains(Hello)) on paragraphsltbuttongt

empty

Remove all child nodes of the set of matched elements f rom the DOM

Added in version 10

empty()jQuery

This method removes not only child (and other descendant) elements but also any text withinthe set of matched elements This is because according to the DOM specif icat ion any stringof text within an element is considered a child node of that element Consider the followingHTML

ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

We can target any element for removal

$(hello)empty()

This will result in a DOM structure with the Hello text deleted

ltdiv class=containergt ltdiv class=hellogtltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo

To avoid memory leaks jQuery removes other constructs such as data and event handlersfrom the child elements before removing the elements themselves

Example 1 Removes all child nodes (including text nodes) f rom all paragraphs

Javascript

$(button)cl ick(function () $(p)empty() )

CSS

p backgroundyellow

HTML

ltpgt Hello ltspangtPersonltspangt lta href=javascriptgtand personltagtltpgt

ltbuttongtCall empty() on above paragraphltbuttongt

replaceAll

Replace each target element with the set of matched elements

Added in version 12

replaceAll(target)jQuery

targetSelector A selector expression indicat ing which element(s) to replace

The replaceAll() method is corollary to replaceWith() but with the source and target reversedConsider this DOM structure

ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

We can create an element then replace other elements with it

$(lth2gtNew headinglth2gt)replaceAll( inner)

This causes all of them to be replaced

ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

Or we could select an element to use as the replacement

$(first)replaceAll( third)

This results in the DOM structure

ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

From this example we can see that the selected element replaces the target by being movedfrom its old locat ion not by being cloned

Example 1 Replace all the paragraphs with bold words

Javascript

$(ltbgtParagraph ltbgt)replaceAll(p) check replaceWith() examples

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

replaceWith

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

Added in version 14

replaceWith(funct ion)jQuery

funct ionFunct ion A funct ion that returns content with which to replace the set ofmatched elements

The replaceWith() method removes content f rom the DOM and inserts new content in its placewith a single call Consider this DOM structure

ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

The second inner ltdivgt could be replaced with the specif ied HTML

$(divsecond)replaceWith(lth2gtNew headinglth2gt)

This results in the structure

ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt lth2gtNew headinglth2gt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

All inner ltdivgt elements could be targeted at once

$(divinner)replaceWith(lth2gtNew headinglth2gt)

This causes all of them to be replaced

ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

An element could also be selected as the replacement

$(divthird)replaceWith($(first))

This results in the DOM structure

ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

This example demonstrates that the selected element replaces the target by being moved fromits old locat ion not by being cloned

The replaceWith() method like most jQuery methods returns the jQuery object so that othermethods can be chained onto it However it must be noted that the original jQuery object isreturned This object refers to the element that has been removed from the DOM not the newelement that has replaced it

As of jQuery 14 replaceWith() can also work on disconnected DOM nodes For example withthe following code replaceWith() returns a jQuery set containing only a paragraph

$(ltdivgt)replaceWith(ltpgtltpgt)

The replaceWith() method can also take a funct ion as its argument

$(divcontainer)replaceWith(function() return $(this)contents())

This results in ltdiv class=containergt being replaced by its three child ltdivgts The return valueof the funct ion may be an HTML string DOM element or jQuery object

Example 1 On click replace the button with a div containing the same word

Javascript

$(button)cl ick(function () $(this)replaceWith( ltdivgt + $(this)text() + ltdivgt ))

CSS

button displayblock margin3px colorred width200px div colorred border2px solid blue width200px margin3px text-aligncenter

HTML

ltbuttongtFirstltbuttongtltbuttongtSecondltbuttongtltbuttongtThirdltbuttongt

Example 2 Replace all paragraphs with bold words

Javascript

$(p)replaceWith( ltbgtParagraph ltbgt )

HTML

ltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

Example 3 On click replace each paragraph with a div that is already in the DOM and selectedwith the $() funct ion Not ice it doesnt clone the object but rather moves it to replace theparagraph

Javascript

$(p)cl ick(function () $(this)replaceWith( $(div) ))

CSS

div border2px solid blue colorred margin3px p border2px solid red colorblue margin3px cursorpointer

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

ltdivgtReplacedltdivgt

Example 4 On button click replace the containing div with its child divs and append the classname of the selected element to the paragraph

Javascript

$(button)bind(click function() var $container = $(divcontainer)replaceWith(function() return $(this)contents() )

$(p)append( $containerattr(class) ))

CSS

container background-color 991 inner color 911

HTML

ltpgt ltbuttongtReplaceltbuttongtltpgtltdiv class=containergt ltdiv class=innergtScoobyltdivgt ltdiv class=innergtDoobyltdivgt ltdiv class=innergtDooltdivgtltdivgt

wrapInner

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

Added in version 14

wrapInner(funct ion(index))jQuery

funct ion(index)Funct ion A callback funct ion which generates a structure to wraparound the content of the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

The wrapInner() funct ion can take any string or object that could be passed to the $() factoryfunct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element The structure will be wrapped around the content ofeach of the elements in the set of matched elements

Consider the following HTML

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

Using wrapInner() we can insert an HTML structure around the content of each inner ltdivgtelements like so

$(inner)wrapInner(ltdiv class=new gt)

The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around the content of each matched element

ltdiv class=containergt ltdiv class=innergt ltdiv class=newgtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=newgtGoodbyeltdivgt ltdivgtltdivgt

The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the content of the correspondingelement For example

$(inner)wrapInner(function() return ltdiv class= + thisnodeValue + gt)

This will cause each ltdivgt to have a class corresponding to the text it wraps

ltdiv class=containergt ltdiv class=innergt ltdiv class=HellogtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=GoodbyegtGoodbyeltdivgt ltdivgtltdivgt

Note When passing a selector string to the wrapInner() funct ion the expected input is wellformed HTML with correct ly closed tags Examples of valid input include

$(elem)wrapInner(ltdiv class=test gt)$(elem)wrapInner(ltdiv class=testgtltdivgt)$(elem)wrapInner(ltdiv class=testgtltdivgt)

Example 1 Selects all paragraphs and wraps a bold tag around each of its contents

Javascript

$(p)wrapInner(ltbgtltbgt)

CSS

p backgroundbbf

HTML

ltpgtHelloltpgt

ltpgtcruelltpgt ltpgtWorldltpgt

Example 2 Wraps a newly created tree of objects around the inside of the body

Javascript

$(body)wrapInner(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

CSS

div border2px green solid margin2px padding2px p backgroundyellow margin2px padding2px

HTML

Plain old text or is it

Example 3 Selects all paragraphs and wraps a bold tag around each of its contents

Javascript

$(p)wrapInner(documentcreateElement(b))

CSS

p background9f9

HTML

ltpgtHelloltpgt

ltpgtcruelltpgt ltpgtWorldltpgt

Example 4 Selects all paragraphs and wraps a jQuery object around each of its contents

Javascript

$(p)wrapInner($(ltspan class=redgtltspangt))

CSS

p background9f9 red colorred

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

wrapAll

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

Added in version 12

wrapAll(wrappingElement)jQuery

wrappingElementStringSelector ElementjQuery

An HTML snippet selector expression jQuery object or DOMelement specifying the structure to wrap around the matchedelements

The wrapAll() funct ion can take any string or object that could be passed to the $() funct ion tospecify a DOM structure This structure may be nested several levels deep but should containonly one inmost element The structure will be wrapped around all of the elements in the set ofmatched elements as a single group

Consider the following HTML

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

Using wrapAll() we can insert an HTML structure around the inner ltdivgt elements like so

$(inner)wrapAll(ltdiv class=new gt)

The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around all matched elements

ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

Example 1 Wrap a new div around all of the paragraphs

Javascript

$(p)wrapAll(ltdivgtltdivgt)

CSS

div border 2px solid blue p backgroundyellow margin4px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

Javascript

$(span)wrapAll(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

CSS

div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

HTML

ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

Example 3 Wrap a new div around all of the paragraphs

Javascript

$(p)wrapAll(documentcreateElement(div))

CSS

div border 2px solid blue p backgroundyellow margin4px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

Javascript

$(p)wrapAll($(doublediv))

CSS

div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

wrap

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

Added in version 14

wrap(funct ion(index))jQuery

funct ion(index)Funct ion A callback funct ion returning the HTML content or jQueryobject to wrap around the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

The wrap() funct ion can take any string or object that could be passed to the $() factory

funct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element A copy of this structure will be wrapped around eachof the elements in the set of matched elements This method returns the original set ofelements for chaining purposes

Consider the following HTML

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

Using wrap() we can insert an HTML structure around the inner ltdivgt elements like so

$(inner)wrap(ltdiv class=new gt)

The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around each matched element

ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=newgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the corresponding element Forexample

$(inner)wrap(function() return ltdiv class= + $(this)text() + gt)

This will cause each ltdivgt to have a class corresponding to the text it wraps

ltdiv class=containergt ltdiv class=Hellogt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=Goodbyegt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

Example 1 Wrap a new div around all of the paragraphs

Javascript

$(p)wrap(ltdivgtltdivgt)

CSS

div border 2px solid blue p backgroundyellow margin4px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

Javascript

$(span)wrap(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

CSS

div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

HTML

ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

Example 3 Wrap a new div around all of the paragraphs

Javascript

$(p)wrap(documentcreateElement(div))

CSS

div border 2px solid blue p backgroundyellow margin4px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

Javascript

$(p)wrap($(doublediv))

CSS

div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

HTML

ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

insertBefore

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

Added in version 10

insertBefore(target)jQuery

targetSelectorElementjQuery

A selector element HTML string or jQuery object the matched set ofelements will be inserted before the element(s) specif ied by thisparameter

The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

Consider the following HTML

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

We can create content and insert it before several elements at once

$(ltpgtTestltpgt)insertBefore(inner)

Each inner ltdivgt element gets this new content

ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Example 1 Inserts all paragraphs before an element with id of foo Same as$( foo)before(p)

Javascript

$(p)insertBefore(foo) check before() examples

CSS

foo backgroundyellow

HTML

ltdiv id=foogtFOOltdivgtltpgtI would l ike to say ltpgt

before

Insert content specif ied by the parameter before each element in the set of matchedelements

Added in version 14

before(funct ion)jQuery

funct ionFunct ion A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert before each element in the set of matched elementsReceives the index posit ion of the element in the set as anargument Within the funct ion this refers to the current element inthe set

The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

Consider the following HTML

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

You can create content and insert it before several elements at once

$(inner)before(ltpgtTestltpgt)

Each inner ltdivgt element gets this new content

ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

In jQuery 14 before() and af ter() will also work on disconnected DOM nodes

$(ltdivgt)before(ltpgtltpgt)

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 prepend() and af ter() before() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

For example the following will insert two new ltdivgts and an exist ing ltdivgt before the f irstparagraph

var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

$(p)first()before($newdiv1 [newdiv2 existingdiv1])

Since before() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so$(p)f irst()before($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

Example 1 Inserts some HTML before all paragraphs

Javascript

$(p)before(ltbgtHelloltbgt)

CSS

p backgroundyellow

HTML

ltpgt is what I saidltpgt

Example 2 Inserts a DOM element before all paragraphs

Javascript

$(p)before( documentcreateTextNode(Hello) )

CSS

p backgroundyellow

HTML

ltpgt is what I saidltpgt

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

Javascript

$(p)before( $(b) )

CSS

p backgroundyellow

HTML

ltpgt is what I saidltpgtltbgtHelloltbgt

insertAfter

Insert every element in the set of matched elements af ter the target

Added in version 10

insertAfter(target)jQuery

targetSelectorElementjQuery

A selector element HTML string or jQuery object the matched set ofelements will be inserted af ter the element(s) specif ied by thisparameter

The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

Consider the following HTML

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

We can create content and insert it af ter several elements at once

$(ltpgtTestltpgt)insertAfter( inner)

Each inner ltdivgt element gets this new content

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

We can also select an element on the page and insert it af ter another

$(h2)insertAfter($(container))

If an element selected this way is inserted elsewhere it will be moved af ter the target (notcloned)

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Example 1 Inserts all paragraphs af ter an element with id of foo Same as $( foo)af ter(p)

Javascript

$(p)insertAfter(foo) check after() examples

CSS

foo backgroundyellow

HTML

ltpgt is what I said ltpgtltdiv id=foogtFOOltdivgt

after

Insert content specif ied by the parameter af ter each element in the set of matched elements

Added in version 14

after(funct ion(index))jQuery

funct ion(index)Funct ion A funct ion that returns an HTML string DOM element(s) orjQuery object to insert af ter each element in the set ofmatched elements Receives the index posit ion of theelement in the set as an argument Within the funct ion thisrefers to the current element in the set

The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

Using the following HTML

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

Content can be created and then inserted af ter several elements at once

$(inner)after(ltpgtTestltpgt)

Each inner ltdivgt element gets this new content

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

An element in the DOM can also be selected and inserted af ter another element

$(container)after($(h2))

If an element selected this way is inserted elsewhere it will be moved rather than cloned

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Inserting Disconnected DOM nodes

As of jQuery 14 before() and af ter() will also work on disconnected DOM nodes For examplegiven the following code

$(ltdivgt)after(ltpgtltpgt)

The result is a jQuery set containing a div and a paragraph in that order That set can befurther manipulated even before it is inserted in the document

$(ltdivgt)after(ltpgtltpgt)addClass(foo) fi lter(p)attr( id bar)html(hello)end()appendTo(body)

This results in the following elements inserted just before the closing ltbodygt tag

ltdiv class=foogtltdivgtltp class=foo id=bargthelloltpgt

Passing a Function

As of jQuery 14 af ter() supports passing a funct ion that returns the elements to insert

$(p)after(function() return ltdivgt + thisclassName + ltdivgt)

This example inserts a ltdivgt af ter each paragraph with each new ltdivgt containing the class

name(s) of its preceding paragraph

Additional Arguments

Similar to other content-adding methods such as prepend() and before() af ter() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

For example the following will insert two new ltdivgts and an exist ing ltdivgt af ter the f irstparagraph

var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

$(p)first()after($newdiv1 [newdiv2 existingdiv1])

Since af ter() can accept any number of addit ional arguments the same result can be achievedby passing in the three ltdivgts as three separate arguments like so $(p)f irst()af ter($newdiv1newdiv2 exist ingdiv1) The type and number of arguments will largely depend on the elementsare collected in the code

Example 1 Inserts some HTML after all paragraphs

Javascript

$(p)after(ltbgtHelloltbgt)

CSS

p backgroundyellow

HTML

ltpgtI would l ike to say ltpgt

Example 2 Inserts a DOM element af ter all paragraphs

Javascript

$(p)after( documentcreateTextNode(Hello) )

CSS

p backgroundyellow

HTML

ltpgtI would l ike to say ltpgt

Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) af ter all paragraphs

Javascript

$(p)after( $(b) )

CSS

p backgroundyellow

HTML

ltbgtHelloltbgtltpgtI would l ike to say ltpgt

prependTo

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

Added in version 10

prependTo(target)jQuery

targetSelectorElementjQuery

A selector element HTML string or jQuery object the matched set ofelements will be inserted at the beginning of the element(s) specif iedby this parameter

The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

Consider the following HTML

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

We can create content and insert it into several elements at once

$(ltpgtTestltpgt)prependTo(inner)

Each inner ltdivgt element gets this new content

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

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

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Example 1 Prepends all spans to the element with the ID foo

CSS

div backgroundyellow

Javascript

$(span)prependTo(foo) check prepend() examples

HTML

ltdiv id=foogtFOOltdivgt

ltspangtI have something to say ltspangt

prepend

Insert content specif ied by the parameter to the beginning of each element in the set ofmatched elements

Added in version 14

prepend(funct ion(index html))jQuery

funct ion(indexhtml)Funct ion

A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the beginning of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

The prepend() method inserts the specif ied content as the f irst child of each element in thejQuery collect ion (To insert it as the last child use append())

The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

Consider the following HTML

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

You can create content and insert it into several elements at once

$(inner)prepend(ltpgtTestltpgt)

Each ltdiv class=innergt element gets this new content

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

You can also select an element on the page and insert it into another

$(container)prepend($(h2))

If a single element selected this way is inserted elsewhere it will be moved into the target (notcloned)

ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

Important If there is more than one target element however cloned copies of the insertedelement will be created for each target af ter the f irst

Additional Arguments

Similar to other content-adding methods such as append() and before() prepend() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

For example the following will insert two new ltdivgts and an exist ing ltdivgt as the f irst threechild nodes of the body

var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

$(body)prepend($newdiv1 [newdiv2 existingdiv1])

Since prepend() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

$(body)prepend($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

Example 1 Prepends some HTML to all paragraphs

Javascript

$(p)prepend(ltbgtHello ltbgt)

CSS

p backgroundyellow

HTML

ltpgtthere friendltpgt

ltpgtamigoltpgt

Example 2 Prepends a DOM Element to all paragraphs

Javascript

$(p)prepend(documentcreateTextNode(Hello ))

CSS

p backgroundyellow

HTML

ltpgtis what Id sayltpgtltpgtis what I saidltpgt

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

Javascript

$(p)prepend( $(b) )

CSS

p backgroundyellow

HTML

ltpgt is what was saidltpgtltbgtHelloltbgt

appendTo

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

Added in version 10

appendTo(target)jQuery

targetSelectorElementjQuery

A selector element HTML string or jQuery object the matched set ofelements will be inserted at the end of the element(s) specif ied by thisparameter

The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

Consider the following HTML

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

We can create content and insert it into several elements at once

$(ltpgtTestltpgt)appendTo(inner)

Each inner ltdivgt element gets this new content

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Example 1 Appends all spans to the element with the ID foo

Javascript

$(span)appendTo(foo) check append() examples

CSS

foo backgroundyellow

HTML

ltspangtI have nothing more to say ltspangt

ltdiv id=foogtFOO ltdivgt

append

Insert content specif ied by the parameter to the end of each element in the set of matchedelements

Added in version 14

append(funct ion(index html))jQuery

funct ion(indexhtml)Funct ion

A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the end of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

The append() method inserts the specif ied content as the last child of each element in thejQuery collect ion (To insert it as the first child use prepend())

The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

Consider the following HTML

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

You can create content and insert it into several elements at once

$(inner)append(ltpgtTestltpgt)

Each inner ltdivgt element gets this new content

lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

Additional Arguments

Similar to other content-adding methods such as prepend() and before() append() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

For example the following will insert two new ltdivgts and an exist ing ltdivgt as the last threechild nodes of the body

var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

$(body)append($newdiv1 [newdiv2 existingdiv1])

Since append() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

$(body)append($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

Example 1 Appends some HTML to all paragraphs

Javascript

$(p)append(ltstronggtHelloltstronggt)

CSS

p backgroundyellow

HTML

ltpgtI would l ike to say ltpgt

Example 2 Appends an Element to all paragraphs

Javascript

$(p)append(documentcreateTextNode(Hello))

CSS

p backgroundyellow

HTML

ltpgtI would l ike to say ltpgt

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

Javascript

$(p)append( $(strong) )

CSS

p backgroundyellow

HTML

ltstronggtHello worldltstronggtltpgtI would l ike to say ltpgt

val see Attributes

val see Attributes

text

Get the combined text contents of each element in the set of matched elements includingtheir descendants

Added in version 10

text()String

Unlike the html() method text() can be used in both XML and HTML documents The result ofthe text() method is a string containing the combined text of all matched elements (Due tovariat ions in the HTML parsers in dif ferent browsers the text returned may vary in newlines andother white space) Consider the following HTML

ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgt ltdivgt

The code $(divdemo-container)text() would produce the following result

Demonstrat ion Box list item 1 list item 2

The text() method cannot be used on form inputs or scripts To set or get the text value ofinput or textarea elements use the val() method To get the value of a script element use thehtml() method

As of jQuery 14 the text() method returns the value of text and CDATA nodes as well aselement nodes

Example 1 Find the text in the f irst paragraph (stripping out the html) then set the html of thelast paragraph to show it is just text (the red bold is gone)

Javascript

var str = $(pfirst)text() $(plast)html(str)

CSS

p colorblue margin8px b colorred

HTML

ltpgtltbgtTestltbgt Paragraphltpgt

ltpgtltpgt

text

Set the content of each element in the set of matched elements to the specif ied text

Added in version 14

text(funct ion(index text))jQuery

funct ion(indextext)Funct ion

A funct ion returning the text content to set Receives the indexposit ion of the element in the set and the old text value as arguments

Unlike the html() method text() 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 willrender correct ly in HTML To do so it calls the DOM method createTextNode() which replacesspecial characters with their HTML ent ity equivalents (such as amplt for lt) Consider the followingHTML

ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgtltdivgt

The code $(divdemo-container)text(ltpgtThis is a test ltpgt) will produce the following DOMoutput

ltdiv class=demo-containergtampltpampgtThis is a testampltpampgtltdivgt

It will appear on a rendered page as though the tags were exposed like this

ltpgtThis is a testltpgt

The text() method cannot be used on input elements For input f ield text use the val() method

As of jQuery 14 the text() method allows us to set the text content by passing in a funct ion

$(ul l i )text(function(index) return item number + (index + 1))

Given an unordered list with three ltligt elements this example will produce the following DOMoutput

ltulgt ltligtitem number 1ltligt ltligtitem number 2ltligt ltligtitem number 3ltligtltulgt

Example 1 Add text to the paragraph (not ice the bold tag is escaped)

Javascript

$(p)text(ltbgtSomeltbgt new text)

CSS

p colorblue margin8px

HTML

ltpgtTest Paragraphltpgt

html see Attributes

html see Attributes

toggleClass see Attributes

removeClass see Attributes

hasClass see Attributes

removeAttr see Attributes

attr see Attributes

attr see Attributes

addClass see Attributes

Data

jQueryhasData

Determine whether an element has any jQuery data associated with it

Added in version 15

jQueryhasData(element)Boolean

elementElement A DOM element to be checked for data

The jQueryhasData() method provides a way to determine if an element current ly has anyvalues that were set using jQuerydata() If no data is associated with an element (there is nodata object at all or the data object is empty) the method returns false otherwise it returnstrue

The primary advantage of jQueryhasData(element) is that it does not create and associate adata object with the element if none current ly exists In contrast jQuerydata(element) alwaysreturns a data object to the caller creat ing one if no data object previously existed

Example 1 Set data on an element and see the results of hasData

Javascript

$(function() var $p = jQuery(p) p = $p[0] $pappend(jQueryhasData(p)+ ) false jQuerydata(p testing 123) $pappend(jQueryhasData(p)+ ) true jQueryremoveData(p testing) $pappend(jQueryhasData(p)+ ) false )

HTML

ltpgtResults ltpgt

jQueryremoveData

Remove a previously-stored piece of data

Added in version 123

jQueryremoveData(element name)jQuery

elementElement A DOM element f rom which to remove data

nameString (opt ional) A string naming the piece of data to remove

Note This is a low-level method you should probably use removeData() instead

The jQueryremoveData() method allows us to remove values that were previously set usingjQuerydata() When called with the name of a key jQueryremoveData() deletes that part icularvalue when called with no arguments all values are removed

Example 1 Set a data store for 2 names then remove one of them

Javascript

var div = $(div)[0]$(spaneq(0))text( + $(div)data(test1))jQuerydata(div test1 VALUE-1)jQuerydata(div test2 VALUE-2)$(spaneq(1))text( + jQuerydata(div test1))jQueryremoveData(div test1)$(spaneq(2))text( + jQuerydata(div test1))$(spaneq(3))text( + jQuerydata(div test2))

CSS

div margin2px colorblue span colorred

HTML

ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt ltdivgtvalue2 after removal ltspangtltspangtltdivgt

jQuerydata

Store arbit rary data associated with the specif ied element Returns the value that was set

Added in version 123

jQuerydata(element key value)Object

elementElement The DOM element to associate with the data

keyString A string naming the piece of data to set

valueObject The new data value

Note This is a low-level method a more convenient data() is also available

The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f ree from memory leaks jQuery ensures that thedata is removed when DOM elements are removed via jQuery methods and when the userleaves the page We can set several dist inct values for a single element and retrieve them later

jQuerydata(documentbody foo 52)jQuerydata(documentbody bar test)

Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

Example 1 Store then retrieve a value from the div element

Javascript

var div = $(div)[0] jQuerydata(div test first 16 last pizza ) $(spanfirst)text(jQuerydata(div test)first) $(spanlast)text(jQuerydata(div test)last)

CSS

div colorblue span colorred

HTML

ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

jQuerydata

Returns value at named data store for the element as set by jQuerydata(element namevalue) or the full data store for the element

Added in version 14

jQuerydata(element)Object

elementElement The DOM element to query for the data

Note This is a low-level method a more convenient data() is also available

Regarding HTML5 data- at t ributes This low-level method does NOT retrieve the data-at t ributes unless the more convenient data() method has already retrieved them

The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f rom memory leaks We can retrieve severaldist inct values for a single element one at a t ime or as a set

alert(jQuerydata( documentbody foo ))alert(jQuerydata( documentbody ))

The above lines alert the data values that were set on the body element If nothing was set onthat element an empty string is returned

Calling jQuerydata(element) retrieves all of the element s associated values as a JavaScriptobject Note that jQuery itself uses this method to store data for internal use such as eventhandlers so do not assume that it contains only data that your own code has stored

Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

Example 1 Get the data named blah stored at for an element

Javascript

$(button)cl ick(function(e) var value div = $(div)[0]

switch ($(button)index(this)) case 0 value = jQuerydata(div blah) break case 1 jQuerydata(div blah hello) value = Stored break case 2 jQuerydata(div blah 86) value = Stored break case 3 jQueryremoveData(div blah) value = Removed break

$(span)text( + value))

CSS

div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

HTML

ltdivgtA divltdivgtltbuttongtGet blah from the divltbuttongtltbuttongtSet blah to helloltbuttongt

ltbuttongtSet blah to 86ltbuttongtltbuttongtRemove blah from the divltbuttongtltpgtThe blah value of this div is ltspangtltspangtltpgt

jQuerydequeue

Execute the next funct ion on the queue for the matched element

Added in version 13

jQuerydequeue(element queueName)jQuery

elementElement A DOM element f rom which to remove and execute a queuedfunct ion

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

Note This is a low-level method you should probably use dequeue() instead

When jQuerydequeue() is called the next funct ion on the queue is removed from the queueand then executed This funct ion should in turn (direct ly or indirect ly) cause jQuerydequeue() tobe called so that the sequence can cont inue

Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

Javascript

$(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $dequeue( this ) ) $(div)animate(left10px top30px 700) )

CSS

div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

HTML

ltbuttongtStartltbuttongt ltdivgtltdivgt

jQueryqueue

Show the queue of funct ions to be executed on the matched element

Added in version 13

jQueryqueue(element queueName)Array

elementElement A DOM element to inspect for an at tached queue

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

Note This is a low-level method you should probably use queue() instead

Example 1 Show the length of the queue

Javascript

$(show)cl ick(function () var n = jQueryqueue( $(div)[0] fx ) $(span)text(Queue length is + nlength) ) function runIt() $(div)show(slow) $(div)animate(left+=2002000) $(div)sl ideToggle(1000) $(div)sl ideToggle(fast) $(div)animate(left-=2001500) $(div)hide(slow) $(div)show(1200) $(div)sl ideUp(normal runIt) runIt()

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue span colorred

HTML

ltbutton id=showgtShow Length of Queueltbuttongt ltspangtltspangt ltdivgtltdivgt

jQueryqueue

Manipulate the queue of funct ions to be executed on the matched element

Added in version 13

jQueryqueue(element queueName callback())jQuery

elementElement A DOM element on which to add a queued funct ion

queueNameString A string containing the name of the queue Defaults to fx thestandard ef fects queue

callback()Funct ion The new funct ion to add to the queue

Note This is a low-level method you should probably use queue() instead

Every element can have one or more queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion

The jQueryqueue() method allows us to direct ly manipulate this queue of funct ions CallingjQueryqueue() with a callback is part icularly useful it allows us to place a new funct ion at theend of the queue

Note that when adding a funct ion with jQueryqueue() we should ensure that jQuerydequeue()is eventually called so that the next funct ion in line executes

Example 1 Queue a custom funct ion

Javascript

$(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=200500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() )

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

HTML

Click here ltdivgtltdivgt

Example 2 Set a queue array to delete the queue

Javascript

$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=2001500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() ) $(stop)cl ick(function () jQueryqueue( $(div)[0] fx [] ) $(div)stop() )

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

HTML

ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

clearQueue

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

Added in version 14

clearQueue(queueName)jQuery

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

When the clearQueue() method is called all funct ions on the queue that have not beenexecuted are removed from the queue When used without an argument clearQueue()removes the remaining funct ions from fx the standard ef fects queue In this way it is similar tostop(true) However while the stop() method is meant to be used only with animat ionsclearQueue() can also be used to remove any funct ion that has been added to a genericjQuery queue with the queue() method

Example 1 Empty the queue

Javascript

$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp())$(stop)cl ick(function () $(div)clearQueue() $(div)stop())

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

HTML

ltbutton id=startgtStartltbuttongtltbutton id=stopgtStopltbuttongtltdivgtltdivgt

removeData

Remove a previously-stored piece of data

Added in version 123

removeData(name)jQuery

nameString (opt ional) A string naming the piece of data to delete

The removeData() method allows us to remove values that were previously set using data()When called with the name of a key removeData() deletes that part icular value when calledwith no arguments all values are removed

NOTE Start ing with jQuery 143 calling removeData() will cause the value of the propertybeing removed to revert to the value of the data at t ribute of the same name in the DOM ratherthan being set to undef ined

Example 1 Set a data store for 2 names then remove one of them

Javascript

$(spaneq(0))text( + $(div)data(test1)) $(div)data(test1 VALUE-1) $(div)data(test2 VALUE-2) $(spaneq(1))text( + $(div)data(test1)) $(div)removeData(test1) $(spaneq(2))text( + $(div)data(test1)) $(spaneq(3))text( + $(div)data(test2))

CSS

div margin2px colorblue span colorred

HTML

ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt

ltdivgtvalue2 after removal ltspangtltspangtltdivgt

data

Store arbit rary data associated with the matched elements

Added in version 143

data(obj)jQuery

objObject An object of key-value pairs of data to update

The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks

We can set several dist inct 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 143 sett ing an element s data object with data(obj) extends the data previouslystored with that element jQuery itself uses the data() method to save informat ion under thenames events and handle and also reserves any data name start ing with an underscore (_)for internal use

Prior to jQuery 143 (start ing in jQuery 14) the data() method completely replaced all datainstead of just extending the data object If you are using third-party plugins it may not beadvisable to completely replace the element s data object since plugins may have also setdata

Due to the way browsers interact with plugins and external code the data() method cannot beused on ltobjectgt (unless it s a Flash plugin) ltappletgt or ltembedgt elements

Example 1 Store then retrieve a value from the div element

Javascript

$(div)data(test first 16 last pizza )$(spanfirst)text($(div)data(test)first)$(spanlast)text($(div)data(test)last)

CSS

div colorblue span colorred

HTML

ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

data

Returns value at named data store for the f irst element in the jQuery collect ion as set bydata(name value)

Added in version 14

data()Object

The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks We can retrieve several dist inctvalues for a single element one at a t ime or as a set

alert($(body)data(foo))alert($(body)data())

The above lines alert the data values that were set on the body element If no data at all wasset on that element undef ined is returned

alert( $(body)data(foo)) undefined$(body)data(bar foobar)alert( $(body)data(foobar)) foobar

HTML 5 data- Attributes

As of jQuery 143 HTML 5 data- at t ributes will be automat ically pulled in to jQuerys data object The treatment of at t ributes with embedded dashes was changed in jQuery 16 to conform tothe W3C HTML5 specif icat ion

For example given the following HTML

ltdiv data-role=page data-last-value=43 data-hidden=true data-options=nameJohngtltdivgt

All of the following jQuery code will work

$(div)data(role) === page$(div)data(lastValue) === 43$(div)data(hidden) === true$(div)data(options)name === John

Every at tempt is made to convert the string to a JavaScript value (this includes booleansnumbers objects arrays and null) otherwise it is lef t as a string To retrieve the valuesat t ribute as a string without any at tempt to convert it use the at t r() method When the dataattribute is an object (starts with ) or array (starts with [) then jQueryparseJSON is used toparse the string it must follow valid JSON syntax including quoted property names The data-at t ributes are pulled in the f irst t ime the data property is accessed and then are no longeraccessed or mutated (all data values are then stored internally in jQuery)

Calling data() with no parameters retrieves all of the values as a JavaScript object This objectcan be safely cached in a variable as long as a new object is not set with data(obj) Using theobject direct ly to get or set values is faster than making individual calls to data() to get or seteach value

var mydata = $(mydiv)data()if ( mydatacount lt 9 ) mydatacount = 43 mydatastatus = embiggened

Example 1 Get the data named blah stored at for an element

Javascript

$(button)cl ick(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))

CSS

div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

HTML

ltdivgtA divltdivgt ltbuttongtGet blah from the divltbuttongt ltbuttongtSet blah to helloltbuttongt

ltbuttongtSet blah to 86ltbuttongt ltbuttongtRemove blah from the divltbuttongt ltpgtThe blah value of this div is ltspangtltspangtltpgt

dequeue

Execute the next funct ion on the queue for the matched elements

Added in version 12

dequeue(queueName)jQuery

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

When dequeue() is called the next funct ion on the queue is removed from the queue and thenexecuted This funct ion should in turn (direct ly or indirect ly) cause dequeue() to be called sothat the sequence can cont inue

Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

Javascript

$(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $(this)dequeue() ) $(div)animate(left10px top30px 700))

CSS

div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

HTML

ltbuttongtStartltbuttongt ltdivgtltdivgt

queue

Show the queue of funct ions to be executed on the matched elements

Added in version 12

queue(queueName)Array

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

Example 1 Show the length of the queue

Javascript

var div = $(div)

function runIt() divshow(slow) divanimate(left+=2002000) divsl ideToggle(1000) divsl ideToggle(fast) divanimate(left-=2001500) divhide(slow) divshow(1200) divsl ideUp(normal runIt)

function showIt() var n = divqueue(fx) $(span)text( nlength ) setTimeout(showIt 100)

runIt()showIt()

CSS

div margin3px width40px height40px positionabsolute left0px top60px backgroundgreen displaynone divnewcolor backgroundblue p colorred

HTML

ltpgtThe queue length is ltspangtltspangtltpgt ltdivgtltdivgt

queue

Manipulate the queue of funct ions to be executed on the matched elements

Added in version 12

queue(queueName callback( next ))jQuery

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

callback( next)Funct ion

The new funct ion to add to the queue with a funct ion to call thatwill dequeue the next item

Every element can have one to many queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion The typical exampleof this is calling mult iple animat ion methods on an element For example

$(foo)sl ideUp()fadeIn()

When this statement is executed the element begins its sliding animat ion immediately but thefading transit ion is placed on the fx queue to be called only once the sliding transit ion iscomplete

The queue() method allows us to direct ly manipulate this queue of funct ions Calling queue()with a callback is part icularly useful it allows us to place a new funct ion at the end of thequeue

This feature is similar to providing a callback funct ion with an animat ion method but does notrequire the callback to be given at the t ime the animat ion is performed

$(foo)sl ideUp()$(foo)queue(function() alert(Animation complete) $(this)dequeue())

This is equivalent to

$(foo)sl ideUp(function() alert(Animation complete))

Note that when adding a funct ion with queue() we should ensure that dequeue() is eventuallycalled so that the next funct ion in line executes

In jQuery 14 the funct ion that s called is passed in another funct ion as the f irst argument thatwhen called automat ically dequeues the next item and keeps the queue moving You would useit like so

$(test)queue(function(next) Do some stuff next())

Example 1 Queue a custom funct ion

Javascript

$(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=200500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() )

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

HTML

Click here ltdivgtltdivgt

Example 2 Set a queue array to delete the queue

Javascript

$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() ) $(stop)cl ick(function () $(div)queue(fx []) $(div)stop() )

CSS

div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

HTML

ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

Forms

submit

Bind an event handler to the submit JavaScript event or t rigger that event on an element

Added in version 10

submit()jQuery

This method is a shortcut for bind(submit handler) in the f irst variat ion and t rigger(submit ) inthe third

The submit event is sent to an element when the user is at tempt ing to submit a form It canonly be at tached to ltformgt elements Forms can be submit ted either by clicking an explicitltinput type=submitgt ltinput type=imagegt or ltbutton type=submitgt or by pressing

Enter when certain form elements have focus

Depending on the browser the Enter key may only cause a form submission if theform has exactly one text field or only when there is a submit button present Theinterface should not rely on a particular behavior for this key unless the issue isforced by observing the keypress event for presses of the Enter key

For example consider the HTML

ltform id=target action=destinationhtmlgt ltinput type=text value=Hello there gt ltinput type=submit value=Go gtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the form

$(target)submit(function() alert(Handler for submit() called) return false)

Now when the form is submit ted the message is alerted This happens prior to the actualsubmission so we can cancel the submit act ion by calling preventDefault () on the event objector by returning false f rom our handler We can trigger the event manually when another elementis clicked

$(other)cl ick(function() $(target)submit())

After this code executes clicks on Trigger the handler will also display the message In addit ionthe default submit act ion on the form will be f ired so the form will be submit ted

The JavaScript submit event does not bubble in Internet Explorer However scripts that rely onevent delegat ion with the submit event will work consistent ly across browsers as of jQuery 14which has normalized the event s behavior

Example 1 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

Javascript

$(form)submit(function() i f ($(inputfirst)val() == correct) $(span)text(Validated)show() return true $(span)text(Not valid)show()fadeOut(1000) return false )

CSS

p margin0 colorblue divp margin-left10px span colorred

HTML

ltpgtType correct to validateltpgt ltform action=javascriptalert(success)gt ltdivgt ltinput type=text gt

ltinput type=submit gt ltdivgt ltformgt ltspangtltspangt

Example 2 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

Javascript

$(form)submit( function () return thissome_flag_variable )

Example 3 To trigger the submit event on the f irst form on the page t ry

Javascript

$(formfirst)submit()

select

Bind an event handler to the select JavaScript event or t rigger that event on an element

Added in version 10

select()jQuery

This method is a shortcut for bind(select handler) in the f irst two variat ions andtrigger(select ) in the third

The select event is sent to an element when the user makes a text select ion inside it Thisevent is limited to ltinput type=textgt f ields and lttextareagt boxes

For example consider the HTML

ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the text input

$(target)select(function() alert(Handler for select() called))

Now when any port ion of the text is selected the alert is displayed Merely set t ing the locat ionof the insert ion point will not t rigger the event To trigger the event manually apply select()without an argument

$(other)cl ick(function() $(target)select())

After this code executes clicks on the Trigger button will also alert the message

Handler for select() called

In addit ion the default select act ion on the f ield will be f ired so the ent ire text f ield will beselected

The method for retrieving the current selected text differs from one browser toanother A number of jQuery plug-ins offer cross-platform solutions

Example 1 To do something when text in input boxes is selected

Javascript

$(input)select( function () $(div)text(Something was selected)show()fadeOut(1000) )

CSS

p colorblue div colorred

HTML

ltpgt

Click and drag the mouse to select text in the inputs ltpgt ltinput type=text value=Some text gt ltinput type=text value=to test on gt

ltdivgtltdivgt

Example 2 To trigger the select event on all input elements t ry

Javascript

$(input)select()

change

Bind an event handler to the change JavaScript event or t rigger that event on an element

Added in version 10

change()jQuery

This method is a shortcut for bind(change handler) in the f irst two variat ions andtrigger(change) in the third

The change event is sent to an element when its value changes This event is limited to ltinputgtelements lttextareagt boxes and ltselectgt elements For select boxes checkboxes and radiobuttons the event is f ired immediately when the user makes a select ion with the mouse butfor the other element types the event is deferred unt il the element loses focus

For example consider the HTML

ltformgt ltinput class=target type=text value=Field 1 gt ltselect class=targetgt ltoption value=option1 selected=selectedgtOption 1ltoptiongt ltoption value=option2gtOption 2ltoptiongt ltselectgtltformgtltdiv id=othergt Trigger the handlerltdivgt

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 opt ion is selected from the dropdown the alert is displayed It is alsodisplayed if you change the text in the f ield and then click away If the f ield loses focus withoutthe contents having changed though the event is not t riggered To trigger the event manuallyapply change() without arguments

$(other)cl ick(function() $( target)change())

After this code executes clicks on Trigger the handler will also alert the message The messagewill display twice because the handler has been bound to the change event on both of theform elements

As of jQuery 14 the change event bubbles in Internet Explorer behaving consistent ly with theevent in other modern browsers

Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

Javascript

$(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) change()

CSS

div colorred

HTML

ltselect name=sweets multiple=multiplegt ltoptiongtChocolateltoptiongt ltoption selected=selectedgtCandyltoptiongt

ltoptiongtTaffyltoptiongt ltoption selected=selectedgtCaramelltoptiongt ltoptiongtFudgeltoptiongt ltoptiongtCookieltoptiongt

ltselectgt ltdivgtltdivgt

Example 2 To add a validity test to all text input elements

Javascript

$(input[type=text])change( function() check input ($(this)val()) for validity here)

blur

Bind an event handler to the blur JavaScript event or t rigger that event on an element

Added in version 10

blur()jQuery

This method is a shortcut for bind(blur handler) in the f irst two variat ions and t rigger(blur) inthe third

The blur event is sent to an element when it loses focus Originally this event was only

applicable to form elements such as ltinputgt In recent browsers the domain of the event hasbeen extended to include all element types An element can lose focus via keyboardcommands such as the Tab key or by mouse clicks elsewhere on the page

For example consider the HTML

ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgtThe event handler can be bound to the first input field$(target)blur(function() alert(Handler for blur() called))

Now if the f irst f ield has the focus clicking elsewhere or tabbing away from it displays the alert

Handler for blur() called

To trigger the event programmatically apply blur() without an argument

$(other)cl ick(function() $(target)blur())

After this code executes clicks on Trigger the handler will also alert the message

The blur event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the blur event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping blur to the focusout event in its eventdelegat ion methods live() and delegate()

Example 1 To trigger the blur event on all paragraphs

Javascript

$(p)blur()

focus

Bind an event handler to the focus JavaScript event or t rigger that event on an element

Added in version 10

focus()jQuery

This method is a shortcut for bind(focus handler) in the f irst and second variat ionsand t rigger(focus) in the third

The focus event is sent to an element when it gains focus This event is implicit lyapplicable to a limited set of elements such as form elements (ltinputgt ltselectgt etc) andlinks (lta hrefgt) In recent browser versions the event can be extended to include allelement types by explicit ly set t ing the element s tabindex property An element can gainfocus via keyboard commands such as the Tab key or by mouse clicks on the element

Elements with focus are usually highlighted in some way by the browser for examplewith a dotted line surrounding the element The focus is used to determine which elementis the f irst to receive keyboard-related events

For example consider the HTML

ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the f irst input f ield

$(target)focus(function() alert(Handler for focus() called))

Now clicking on the f irst f ield or tabbing to it f rom another f ield displays the alert

Handler for focus() called

We can trigger the event when another element is clicked

$(other)cl ick(function() $(target)focus())

After this code executes clicks on Trigger the handler will also alert the message

The focus event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the focus event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping focus to the focusin event in its event

delegat ion methods live() and delegate()

Triggering the focus on hidden elements causes an error in Internet ExplorerTake care to only call focus() without parameters on elements that are visible

Example 1 Fire focus

CSS

span displaynone

Javascript

$(input)focus(function () $(this)next(span)css(display inl ine)fadeOut(1000) )

HTML

ltpgtltinput type=text gt ltspangtfocus fireltspangtltpgt

ltpgtltinput type=password gt ltspangtfocus fireltspangtltpgt

Example 2 To stop people f rom writ ing in text input boxes t ry

Javascript

$(input[type=text])focus(function() $(this)blur())

Example 3 To focus on a login input box with id login on page startup t ry

Javascript

$(document)ready(function() $(login)focus())

serializeArray

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

Added in version 12

serializeArray()Array

The serializeArray() method creates a JavaScript array of objects ready to be encoded as aJSON string It operates on a jQuery object represent ing a set of form elements The formelements can be of several types

ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

The serializeArray() method uses the standard W3C rules for successful controls to determinewhich elements it should include in part icular the element cannot be disabled and must containa name attribute No submit button value is serialized since the form was not submit ted using abutton Data f rom f ile select elements is not serialized

This method can act on a jQuery object that has selected individual form elements such asltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgt tag itselffor serializat ion

$(form)submit(function() consolelog($(this)serial izeArray()) return false)

This produces the following data structure (provided that the browser supports consolelog)

[ name a value 1 name b value 2 name c value 3 name d value 4 name e value 5 ]

Example 1 Get the values from a form iterate through them and append them to a resultsdisplay

Javascript

function showValues() var fields = $(input)serial izeArray() $(results)empty() jQueryeach(fields function(i field) $(results)append(fieldvalue + ) )

$(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

CSS

body select font-size14px form margin5px p colorred margin5px b colorblue

HTML

ltpgtltbgtResultsltbgt ltspan id=resultsgtltspangtltpgt

ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

ltselectgt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

ltlabel for=ch1gtcheck1ltlabelgt ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

ltlabel for=ch2gtcheck2ltlabelgt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

ltlabel for=r2gtradio2ltlabelgt ltformgt

serialize

Encode a set of form elements as a string for submission

Added in version 10

serialize()String

The serialize() method creates a text string in standard URL-encoded notat ion It operates ona jQuery object represent ing a set of form elements The form elements can be of severaltypes

ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

The serialize() method can act on a jQuery object that has selected individual form elementssuch as ltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgttag itself for serializat ion

$(form)submit(function() alert($(this)serial ize()) return false)

This produces a standard-looking query string

a=1ampb=2ampc=3ampd=4ampe=5

Warning select ing both the form and its children will cause duplicates in the serialized string

Note Only successful controls are serialized to the string No submit button value is serializedsince the form was not submit ted using a button For a form element s value to be included inthe serialized string the element must have a name attribute Values from checkboxes andradio buttons (inputs of type radio or checkbox) are included only if they are checked Datafrom f ile select elements is not serialized

Example 1 Serialize a form to a query string that could be sent to a server in an Ajax request

Javascript

function showValues() var str = $(form)serial ize() $(results)text(str) $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

CSS

body select font-size12px form margin5px p colorred margin5px font-size14px b colorblue

HTML

ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

ltbr gt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

ltlabel for=ch1gtcheck1ltlabelgt

ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

ltlabel for=ch2gtcheck2ltlabelgtltbr gt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

ltlabel for=r2gtradio2ltlabelgt ltformgt ltpgtlttt id=resultsgtltttgtltpgt

jQueryparam

Create a serialized representat ion of an array or object suitable for use in a URL query string orAjax request

Added in version 14

jQueryparam(obj t radit ional)String

objArray Object An array or object to serialize

t radit ionalBoolean A Boolean indicat ing whether to perform a tradit ional shallowserializat ion

This funct ion is used internally to convert form element values into a serialized stringrepresentat ion (See serialize() for more informat ion)

As of jQuery 13 the return value of a funct ion is used instead of the funct ion as a String

As of jQuery 14 the $param() method serializes deep objects recursively to accommodatemodern script ing languages and frameworks such as PHP and Ruby on Rails You can disablethis funct ionality globally by sett ing jQueryajaxSett ingst radit ional = t rue

If the object passed is in an Array it must be an array of objects in the format returned byserializeArray()

[namefirstvalueRicknamelastvalueAstleynamejobvalueRock Star]

Note Because some frameworks have limited ability to parse serialized arraysdevelopers should exercise caution when passing an obj argument that containsobjects or arrays nested within another array

Note Because there is no universally agreed-upon specification for param stringsit is not possible to encode complex data structures using this method in a mannerthat works ideally across all languages supporting such input Until such time thatthere is the $param method will remain in its current form

In jQuery 14 HTML5 input elements are also serialized

We can display a query string representat ion of an object and a URI-decoded version of the

same as follows

var myObject = a one 1 two 2 three 3 b [123]var recursiveEncoded = $param(myObject)var recursiveDecoded = decodeURIComponent($param(myObject))

alert(recursiveEncoded)alert(recursiveDecoded)

The values of recursiveEncoded and recursiveDecoded are alerted as follows

a5Bone5D=1ampa5Btwo5D=2ampa5Bthree5D=3ampb5B5D=1ampb5B5D=2ampb5B5D=3

a[one]=1ampa[two]=2ampa[three]=3ampb[]=1ampb[]=2ampb[]=3

To emulate the behavior of $param() prior to jQuery 14 we can set the t radit ional argument totrue

var myObject = a one 1 two 2 three 3 b [123]var shallowEncoded = $param(myObject true)var shallowDecoded = decodeURIComponent(shallowEncoded)

alert(shallowEncoded)alert(shallowDecoded)

The values of shallowEncoded and shallowDecoded are alerted as follows

a=5Bobject+Object5Dampb=1ampb=2ampb=3

a=[object+Object ]ampb=1ampb=2ampb=3

Example 1 Serialize a keyvalue object

Javascript

var params = width1680 height1050 var str = jQueryparam(params) $(results)text(str)

CSS

div colorred

HTML

ltdiv id=resultsgtltdivgt

Example 2 Serialize a few complex objects

Javascript

lt=132 $param( a [234] ) a=2ampa=3ampa=4 gt=14$param( a [234] ) a[]=2ampa[]=3ampa[]=4

lt=132 $param( a b1c2 d [34 e5 ] ) a=[object+Object]ampd=3ampd=4ampd=[object+Object] gt=14 $param( a b1c2 d [34 e5 ] ) a[b]=1ampa[c]=2ampd[]=3ampd[]=4ampd[2][e]=5

CSS

div colorred

val see Attributes

val see Attributes

Events

toggle

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

Added in version 10

toggle(handler(eventObject) handler(eventObject) handler(eventObject))jQuery

handler(eventObject)Funct ion A funct ion to execute every even t ime the element isclicked

handler(eventObject)Funct ion A funct ion to execute every odd t ime the element isclicked

handler(eventObject)Funct ion (opt ional) Addit ional handlers to cycle through af terclicks

The toggle() method binds a handler for the click event so the rules out lined for the t riggeringof click apply here as well

For example consider the HTMLltdiv id=targetgt Click hereltdivgt

Event handlers can then bebound to the ltdivgt

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

First handler for toggle() called

Second handler for toggle() called

First handler for toggle() called

Second handler for toggle() called

First handler for toggle() called

If more than two handlers are provided toggle() will cycle among all of them For example ifthere are three handlers then the f irst handler will be called on the f irst click the fourth clickthe seventh click and so on

Note jQuery also provides an animation method named toggle() that toggles the

visibility of elements Whether the animation or the event method is fired dependson the set of arguments passed

The toggle() method is provided for convenience It is relat ively straightforward to implementthe same behavior by hand and this can be necessary if the assumptions built into toggle()prove limit ing For example toggle() is not guaranteed to work correct ly if applied twice to thesame element Since toggle() internally uses a click handler to do its work we must unbind clickto remove a behavior at tached with toggle() so other click handlers can be caught in thecrossf ire The implementat ion also calls preventDefault () on the event so links will not befollowed and buttons will not be clicked if toggle() has been called on the element

Example 1 Click to toggle highlight on the list item

Javascript

$(l i)toggle( function () $(this)css(list-style-typedisc colorblue) function () $(this)css(list-style-typedisc colorred) function () $(this)css(list-style-type color) )

CSS

ul margin10px l ist-styleinside circle font-weightbold l i cursorpointer

HTML

ltulgt ltligtGo to the storeltligt ltligtPick up dinnerltligt ltligtDebug crashltligt

ltligtTake a jogltligt ltulgt

Example 2 To toggle a style on table cells

Javascript

Javascript

$(td)toggle( function () $(this)addClass(selected) function () $(this)removeClass(selected) )

eventnamespace

The namespace specif ied when the event was triggered

Added in version 143

This will likely be used primarily by plugin authors who wish to handle tasks dif ferent lydepending on the event namespace used

Example 1 Determine the event namespace used

Javascript

$(p)bind(testsomething function(event) alert( eventnamespace ))$(button)cl ick(function(event) $(p)trigger(testsomething))

HTML

ltbuttongtdisplay eventnamespaceltbuttongtltpgtltpgt

undelegate

Remove a handler f rom the event for all elements which match the current selector now or inthe future based upon a specif ic set of root elements

Added in version 16

undelegate(namespace)jQuery

namespaceString A string containing a namespace to unbind all events f rom

Undelegate is a way of removing event handlers that have been bound using delegate() Itworks virtually ident ically to die() with the addit ion of a selector f ilter argument (which isrequired for delegat ion to work)

Example 1 Can bind and unbind events to the colored button

Javascript

function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(body)delegate(theone cl ick aClick) find(theone)text(Can Click))$(unbind)cl ick(function () $(body)undelegate(theone cl ick aClick) find(theone)text(Does nothing))

CSS

button margin5px buttontheone colorred backgroundyellow

HTML

ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongtltdiv style=displaynonegtClickltdivgt

Example 2 To unbind all delegated events f rom all paragraphs write

Javascript

$(p)undelegate()

Example 3 To unbind all delegated click events f rom all paragraphs write

Javascript

$(p)undelegate( cl ick )

Example 4 To undelegate just one previously bound handler pass the funct ion in as the third

argument

Javascript

var foo = function () code to handle some kind of event

now foo wil l be called when paragraphs are cl icked $(body)delegate(p cl ick foo)

foo wil l no longer be called$(body)undelegate(p cl ick foo)

Example 5 To unbind all delegated events by their namespace

Javascript

var foo = function () code to handle some kind of event

delegate events under the whatever namespace$(form)delegate(button cl ickwhatever foo)

$(form)delegate(input[type=text] keypresswhatever foo)

unbind all events delegated under the whatever namespace

$(form)undelegate(whatever)

delegate

Attach a handler to one or more events for all elements that match the selector now or in thefuture based on a specif ic set of root elements

Added in version 143

delegate(selector events)jQuery

selectorString A selector to f ilter the elements that t rigger the event

eventsMap A map of one or more event types and funct ions to execute for them

Delegate is an alternat ive to using the live() method allowing for each binding of eventdelegat ion to specif ic DOM elements For example the following delegate code

$(table)delegate(td hover function() $(this)toggleClass(hover))

Is equivalent to the following code writ ten using live()

$(table)each(function() $(td this)l ive(hover function() $(this)toggleClass(hover) ))

See also the undelegate() method for a way of removing event handlers added in delegate()

Passing and handling event data works the same way as it does for bind()

Example 1 Click a paragraph to add another Note that delegate() binds the click event to allparagraphs - even new ones

Javascript

$(body)delegate(p cl ick function() $(this)after(ltpgtAnother paragraphltpgt) )

CSS

p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

HTML

ltpgtClick meltpgt

ltspangtltspangt

Example 2 To display each paragraphs text in an alert box whenever it is clicked

Javascript

$(body)delegate(p cl ick function() alert( $(this)text() ))

Example 3 To cancel a default act ion and prevent it f rom bubbling up return false

Javascript

$(body)delegate(a cl ick function() return false )

Example 4 To cancel only the default act ion by using the preventDefault method

Javascript

$(body)delegate(a cl ick function(event) eventpreventDefault())

Example 5 Can bind custom events too

Javascript

$(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)cl ick(function () $(p)trigger(myCustomEvent) )

CSS

p colorred span colorblue

HTML

ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

jQueryproxy

Takes a funct ion and returns a new one that will always have a part icular context

Added in version 14

jQueryproxy(context name)Funct ion

context Object The object to which the context of the funct ion should be set

nameString The name of the funct ion whose context will be changed (should be aproperty of the context object)

This method is most useful for at taching event handlers to an element where the context ispoint ing back to a dif ferent object Addit ionally jQuery makes sure that even if you bind thefunct ion returned from jQueryproxy() it will st ill unbind the correct funct ion if passed theoriginal

Example 1 Change the context of funct ions bound to a click handler using the funct ioncontext signature Unbind the f irst handler af ter f irst click

HTML

ltpgtltbutton type=button id=testgtTestltbuttongtltpgtltdiv id=loggtltdivgt

Javascript

var me = type zombie test function(event) Without proxy `this` would refer to the event target use eventtarget to reference that element var element = eventtarget $(element)css(background-color red)

With proxy `this` refers to the me object encapsulating this function $(log)append( Hello + thistype + ltbrgt ) $(test)unbind(click thistest)

var you = type person test function(event) $(log)append( thistype + )

execute youtest() in the context of the `you` object no matter where it is called i e the `this` keyword wil l refer to `you`var youClick = $proxy( youtest you )

attach click handlers to test$(test) this === zombie handler unbound after first cl ick cl ick( $proxy( metest me ) ) this === person cl ick( youClick ) this === zombie cl ick( $proxy( youtest me ) ) this === ltbuttongt element cl ick( youtest )

Example 2 Enforce the context of the funct ion using the context funct ion name signatureUnbind the handler af ter f irst click

HTML

ltpgtltbutton id=testgtTestltbuttongtltpgt ltp id=loggtltpgt

Javascript

var obj = name John test function() $(log)append( thisname ) $(test)unbind(click objtest)

$(test)cl ick( jQueryproxy( obj test ) )

focusout

Bind an event handler to the focusout JavaScript event

Added in version 143

focusout(eventData handler(eventObject))jQuery

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

This method is a shortcut for bind(focusout handler)

The focusout event is sent to an element when it or any element inside of it loses focus Thisis dist inct f rom the blur event in that it supports detect ing the loss of focus from parentelements (in other words it supports event bubbling)

This event will likely be used together with the focusin event

Example 1 Watch for a loss of focus to occur inside paragraphs and note the dif ferencebetween the focusout count and the blur count

CSS

inputs float left margin-right 1em

inputs p margin-top 0

Javascript

var fo = 0 b = 0$(p)focusout(function() fo++ $(fo) text(focusout fired + fo + x))blur(function() b++ $(b) text(blur fired + b + x) )

HTML

ltdiv class=inputsgt ltpgt ltinput type=text gtltbr gt ltinput type=text gt ltpgt ltpgt ltinput type=password gt ltpgtltdivgtltdiv id=fogtfocusout fireltdivgtltdiv id=bgtblur fireltdivgt

focusin

Bind an event handler to the focusin JavaScript event

Added in version 143

focusin(eventData handler(eventObject))jQuery

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

This method is a shortcut for bind(focusin handler)

The focusin event is sent to an element when it or any element inside of it gains focus This isdist inct f rom the focus event in that it supports detect ing the focus event on parent elements(in other words it supports event bubbling)

This event will likely be used together with the focusout event

Example 1 Watch for a focus to occur within the paragraphs on the page

CSS

span displaynone

Javascript

$(p)focusin(function() $(this)find(span)css(display inl ine)fadeOut(1000) )

HTML

ltpgtltinput type=text gt ltspangtfocusin fireltspangtltpgtltpgtltinput type=password gt ltspangtfocusin fireltspangtltpgt

eventisImmediatePropagationStopped

Returns whether eventstopImmediatePropagat ion() was ever called on this event object

Added in version 13

eventisImmediatePropagat ionStopped()Boolean

This property was introduced in DOM level 3

Example 1 Checks whether eventstopImmediatePropagat ion() was called

Javascript

function immediatePropStopped(e) var msg = i f ( eisImmediatePropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

$(button)cl ick(function(event) immediatePropStopped(event) eventstopImmediatePropagation() immediatePropStopped(event))

HTML

ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

eventstopImmediatePropagation

Keeps the rest of the handlers f rom being executed and prevents the event f rom bubbling upthe DOM tree

Added in version 13

eventstopImmediatePropagat ion()

In addit ion to keeping any addit ional handlers on an element f rom being executed this methodalso stops the bubbling by implicit ly calling eventstopPropagat ion() To simply prevent theevent f rom bubbling to ancestor elements but allow other event handlers to execute on thesame element we can use eventstopPropagat ion() instead

Use eventisImmediatePropagat ionStopped() to know whether this method was ever called (onthat event object)

Example 1 Prevents other event handlers f rom being called

CSS

p height 30px width 150px background-color ccf div height 30px width 150px background-color cfc

Javascript

$(p)cl ick(function(event) eventstopImmediatePropagation())$(p)cl ick(function(event) This function wont be executed $(this)css(background-color f00)) $(div)cl ick(function(event) This function wil l be executed $(this)css(background-color f00))

HTML

ltpgtparagraphltpgtltdivgtdivisionltdivgt

eventisPropagationStopped

Returns whether eventstopPropagat ion() was ever called on this event object

Added in version 13

eventisPropagat ionStopped()Boolean

This event method is described in the W3C DOM Level 3 specif icat ion

Example 1 Checks whether eventstopPropagat ion() was called

Javascript

function propStopped(e) var msg = i f ( eisPropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

$(button)cl ick(function(event) propStopped(event) eventstopPropagation() propStopped(event))

HTML

ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

eventstopPropagation

Prevents the event f rom bubbling up the DOM tree prevent ing any parent handlers f rom beingnot if ied of the event

Added in version 10

eventstopPropagat ion()

We can use eventisPropagat ionStopped() to determine if this method was ever called (on thatevent object)

This method works for custom events t riggered with t rigger() as well

Note that this will not prevent other handlers on the same element f rom running

Example 1 Kill the bubbling on the click event

Javascript

$(p)cl ick(function(event) eventstopPropagation() do something)

eventisDefaultPrevented

Returns whether eventpreventDefault () was ever called on this event object

Added in version 13

eventisDefaultPrevented()Boolean

Example 1 Checks whether eventpreventDefault () was called

Javascript

$(a)cl ick(function(event) alert( eventisDefaultPrevented() ) false eventpreventDefault() alert( eventisDefaultPrevented() ) true)

eventpreventDefault

If this method is called the default act ion of the event will not be triggered

Added in version 10

eventpreventDefault ()undef ined

For example clicked anchors will not take the browser to a new URL We can useeventisDefaultPrevented() to determine if this method has been called by an event handlerthat was triggered by this event

Example 1 Cancel the default act ion (navigat ion) of the click

Javascript

$(a)cl ick(function(event) eventpreventDefault() $(ltdivgt) append(default + eventtype + prevented) appendTo(log))

HTML

lta href=httpjquerycomgtdefault cl ick action is preventedltagtltdiv id=loggtltdivgt

eventtimeStamp

The dif ference in milliseconds between the t ime an event is t riggered and January 1 1970

Added in version 126

This property can be useful for prof iling the performance of certain jQuery funct ions by gett ingthe eventt imeStamp value at two points in the code and not ing the dif ference

Example 1 Display the t ime since the click handler last executed

CSS

div height 100px width 300px margin 10px background-color ffd overflow auto

Javascript

var last diff$(div)cl ick(function(event) if ( last ) diff = eventtimeStamp - last $(div)append(time since last event + diff + ltbrgt) else $(div)append(Click againltbrgt) last = eventtimeStamp)

HTML

ltdivgtClickltdivgt

eventresult

The last value returned by an event handler that was triggered by this event unless the valuewas undef ined

Added in version 13

This property can be useful for gett ing previous return values of custom events

Example 1 Display previous handlers return value

Javascript

$(button)cl ick(function(event) return hey)$(button)cl ick(function(event) $(p)html( eventresult ))

HTML

ltbuttongtdisplay eventresultltbuttongtltpgtltpgt

eventwhich

For key or button events this at t ribute indicates the specif ic button or key that was pressed

Added in version 113

eventwhich normalizes eventkeyCode and eventcharCode It is recommended to watcheventwhich for keyboard key input For more detail read about eventcharCode on the MDC

Example 1 Log what key was depressed

Javascript

$(whichkey)bind(keydownfunction(e) $(log)html(etype + + ewhich ))

HTML

ltinput id=whichkey value=type somethinggtltdiv id=loggtltdivgt

Results

keydown 74

eventpageY

The mouse posit ion relat ive to the top edge of the document

Added in version 104

Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthis if rame)

CSS

body background-color eef div padding 20px

HTML

ltdiv id=loggtltdivgt

Javascript

$(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

eventpageX

The mouse posit ion relat ive to the lef t edge of the document

Added in version 104

Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthe if rame)

CSS

body background-color eef div padding 20px

HTML

ltdiv id=loggtltdivgt

Javascript

$(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

eventcurrentTarget

The current DOM element within the event bubbling phase

Added in version 13

This property will typically be equal to the this of the funct ion

If you are using jQueryproxy or another form of scope manipulation this will be equal towhatever context you have provided not eventcurrentTarget

Example 1 Alert that currentTarget matches the `this` keyword

Javascript

$(p)cl ick(function(event) alert( eventcurrentTarget === this ) true)

eventrelatedTarget

The other DOM element involved in the event if any

Added in version 114

For mouseout indicates the element being entered for mouseover indicates the elementbeing exited

Example 1 On mouseout of anchors alert the element type being entered

Javascript

$(a)mouseout(function(event) alert(eventrelatedTargetnodeName) DIV)

eventdata

The opt ional data passed to jQueryfnbind when the current execut ing handler was bound

Added in version 11

Example 1 The descript ion of the example

Javascript

$(a)each(function(i) $(this)bind(cl ick indexi function(e) alert(my index is + edataindex) ))

eventtarget

The DOM element that init iated the event

Added in version 10

The target property can be the element that registered for the event or a descendant of it It isof ten useful to compare eventtarget to this in order to determine if the event is being handleddue to event bubbling This property is very useful in event delegat ion when events bubble

Example 1 Display the tags name on click

Javascript

$(body)cl ick(function(event) $(log)html(clicked + eventtargetnodeName))

CSS

span strong p padding 8px display block border 1px solid 999

HTML

ltdiv id=loggtltdivgtltdivgt ltpgt ltstronggtltspangtclickltspangtltstronggt ltpgtltdivgt

Example 2 Implements a simple event delegat ion The click handler is added to an unorderedlist and the children of its li children are hidden Clicking one of the li children toggles (seetoggle()) their children

Javascript

function handler(event) var $target = $(eventtarget) i f( $targetis( l i) ) $targetchildren()toggle() $(ul)cl ick(handler)find(ul)hide()

HTML

ltulgt ltligtitem 1 ltulgt ltligtsub item 1-altligt ltligtsub item 1-bltligt ltulgt ltl igt ltligtitem 2 ltulgt ltligtsub item 2-altligt ltligtsub item 2-bltligt ltulgt ltl igt ltulgt

eventtype

Describes the nature of the event

Added in version 10

Example 1 On all anchor clicks alert the event type

Javascript

$(a)cl ick(function(event) alert(eventtype) cl ick)

keydown

Bind an event handler to the keydown JavaScript event or t rigger that event on an element

Added in version 10

keydown()jQuery

This method is a shortcut for bind(keydown handler) in the f irst and second variat ions and

t rigger(keydown) in the third

The keydown event is sent to an element when the user f irst presses a key on the keyboard Itcan be at tached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

For example consider the HTML

ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the input f ield

$(target)keydown(function() alert(Handler for keydown() called))

Now when the insert ion point is inside the f ield pressing a key displays the alert

Handler for keydown() called

To trigger the event manually apply keydown() without an argument

$(other)cl ick(function() $(target)keydown())

After this code executes clicks on Trigger the handler will also alert the message

If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

Example 1 Show the event object for the keydown handler when a key is pressed in the input

Javascript

var xTriggered = 0$(target)keydown(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keydown() called + xTriggered + time(s) $print(msg html) $print(event))

$(other)cl ick(function() $(target)keydown())

CSS

fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

HTML

ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

scroll

Bind an event handler to the scroll JavaScript event or t rigger that event on an element

Added in version 10

scroll()jQuery

This method is a shortcut for bind(scroll handler) in the f irst and second variat ions andtrigger(scroll) in the third

The scroll event is sent to an element when the user scrolls to a dif ferent place in the elementIt applies to window objects but also to scrollable f rames and elements with the overf low CSSproperty set to scroll (or auto when the element s explicit height or width is less than the heightor width of its contents)

For example consider the HTML

ltdiv id=target style=overflow scroll width 200px height 100pxgt 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 al iquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt moll it anim id est laborumltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The style def init ion is present to make the target element small enough to be scrollable

The scroll event handler can bebound to this element

$(target)scroll(function() $(log)append(ltdivgtHandler for scroll() calledltdivgt))

Now when the user scrolls the text up or down one or more messages are appended to ltdiv

id=loggtltdivgt

Handler for scroll() called

To trigger the event manually apply scroll() without an argument

$(other)cl ick(function() $(target)scroll())

After this code executes clicks on Trigger the handler will also append the message

A scroll event is sent whenever the element s scroll posit ion changes regardless of the causeA mouse click or drag on the scroll bar dragging inside the element pressing the arrow keys orusing the mouses scroll wheel could cause this event

Example 1 To do something when your page is scrolled

Javascript

$(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(window)scroll(function () $(span)css(display inl ine)fadeOut(slow) )

CSS

div colorblue p colorgreen span colorred displaynone

HTML

ltdivgtTry scroll ing the iframeltdivgt ltpgtParagraph - ltspangtScroll happenedltspangtltpgt

resize

Bind an event handler to the resize JavaScript event or t rigger that event on an element

Added in version 10

resize()jQuery

This method is a shortcut for bind(resize handler) in the f irst and second variat ions andtrigger(resize) in the third

The resize event is sent to the window element when the size of the browser window changes

$(window)resize(function() $(log)append(ltdivgtHandler for resize() calledltdivgt))

Now whenever the browser windows size is changed the message is appended to ltdivid=loggt one or more t imes depending on the browser

Code in a resize handler should never rely on the number of t imes the handler is calledDepending on implementat ion resize events can be sent cont inuously as the resizing is inprogress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safariand Chrome) or only once at the end of the resize operat ion (the typical behavior in someother browsers such as Opera)

Example 1 To see the window width while (or af ter) it is resized t ry

Javascript

$(window)resize(function() $(body)prepend(ltdivgt + $(window)width() + ltdivgt))

keyup

Bind an event handler to the keyup JavaScript event or t rigger that event on an element

Added in version 10

keyup()jQuery

This method is a shortcut for bind(keyup handler) in the f irst two variat ions andtrigger(keyup) in the third

The keyup event is sent to an element when the user releases a key on the keyboard It can beattached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

For example consider the HTML

ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the input f ield

$(target)keyup(function() alert(Handler for keyup() called))

Now when the insert ion point is inside the f ield and a key is pressed and released the alert isdisplayed

Handler for keyup() called

To trigger the event manually apply keyup() without arguments

$(other)cl ick(function() $(target)keyup())

After this code executes clicks on Trigger the handler will also alert the message

If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

Example 1 Show the event object for the keyup handler when a key is released in the input

Javascript

var xTriggered = 0$(target)keyup(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keyup() called + xTriggered + time(s) $print(msg html) $print(event))

$(other)cl ick(function() $(target)keyup())

CSS

fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

HTML

ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

keypress

Bind an event handler to the keypress JavaScript event or t rigger that event on an element

Added in version 10

keypress()jQuery

Note as the keypress event isnt covered by any of f icial specif icat ion the actual behaviorencountered when using it may dif fer across browsers browser versions and plat forms

This method is a shortcut for bind(keypress handler) in the f irst two variat ions andtrigger(keypress) in the third

The keypress event is sent to an element when the browser registers keyboard input This issimilar to the keydown event except in the case of key repeats If the user presses and holds akey a keydown event is t riggered once but separate keypress events are t riggered for eachinserted character In addit ion modif ier keys (such as Shif t ) t rigger keydown events but notkeypress events

A keypress event handler can be at tached to any element but the event is only sent to theelement that has the focus Focusable elements can vary between browsers but formelements can always get focus so are reasonable candidates for this event type

For example consider the HTML

ltformgt ltfieldsetgt ltinput id=target type=text value=Hello there gt ltfieldsetgtltformgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be bound to the input f ield

$(target)keypress(function() alert(Handler for keypress() called))

Now when the insert ion point is inside the f ield pressing a key displays the alert

Handler for keypress() called

The message repeats if the key is held down To trigger the event manually apply keypress()without an argument

$(other)cl ick(function() $(target)keypress())

After this code executes clicks on Trigger the handler will also alert the message

If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

To determine which character was entered examine the event object that is passed to thehandler funct ion While browsers use dif fering propert ies to store this informat ion jQuerynormalizes the which property so you can reliably use it to retrieve the character code

Note that keydown and keyup provide a code indicat ing which key is pressed while keypressindicates which character was entered For example a lowercase a will be reported as 65 bykeydown and keyup but as 97 by keypress An uppercase A is reported as 65 by all eventsBecause of this dist inct ion when catching special keystrokes such as arrow keys keydown() orkeyup() is a better choice

Example 1 Show the event object when a key is pressed in the input Note This demo relies ona simple $print() plugin (ht tpapijquerycomscriptseventsjs) for the event object s output

Javascript

var xTriggered = 0$(target)keypress(function(event) if ( eventwhich == 13 ) eventpreventDefault() xTriggered++ var msg = Handler for keypress() called + xTriggered + time(s) $print( msg html ) $print( event ))

$(other)cl ick(function() $(target)keypress())

CSS

fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

HTML

ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript src=httpapijquerycomscriptseventsjsgtltscriptgt

submit see Forms

select see Forms

change see Forms

blur see Forms

focus see Forms

mousemove

Bind an event handler to the mousemove JavaScript event or t rigger that event on anelement

Added in version 10

mousemove()jQuery

This method is a shortcut for bind(mousemove handler) in the f irst two variat ions andtrigger(mousemove) in the third

The mousemove event is sent to an element when the mouse pointer moves inside theelement Any HTML element can receive this event

For example consider the HTML

ltdiv id=targetgt Move hereltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The event handler can be bound to the target

$(target)mousemove(function(event) var msg = Handler for mousemove() called at msg += eventpageX + + eventpageY $(log)append(ltdivgt + msg + ltdivgt))

Now when the mouse pointer moves within the target button the messages are appended toltdiv id=loggt

Handler for mousemove() called at (399 48)

Handler for mousemove() called at (398 46)

Handler for mousemove() called at (397 44)

Handler for mousemove() called at (396 42)

To trigger the event manually apply mousemove() without an argument

$(other)cl ick(function() $(target)mousemove())

After this code executes clicks on the Trigger button will also append the message

Handler for mousemove() called at (undef ined undef ined)

When tracking mouse movement you usually need to know the actual posit ion of the mousepointer The event object that is passed to the handler contains some informat ion about themouse coordinates Propert ies such as clientX of fsetX and pageX are available but supportfor them dif fers between browsers Fortunately jQuery normalizes the pageX and pageYpropert ies so that they can be used in all browsers These propert ies provide the X and Ycoordinates of the mouse pointer relat ive to the top-lef t corner of the document as illustratedin the example output above

Keep in mind that the mousemove event is t riggered whenever the mouse pointer moves evenfor a pixel This means that hundreds of events can be generated over a very small amount oft ime If the handler has to do any signif icant processing or if mult iple handlers for the eventexist this can be a serious performance drain on the browser It is important therefore toopt imize mousemove handlers as much as possible and to unbind them as soon as they areno longer needed

A common pattern is to bind the mousemove handler f rom within a mousedown hander and tounbind it f rom a corresponding mouseup handler If implement ing this sequence of eventsremember that the mouseup event might be sent to a dif ferent HTML element than themousemove event was To account for this the mouseup handler should typically be bound toan element high up in the DOM tree such as ltbodygt

Example 1 Show the mouse coordinates when the mouse is moved over the yellow divCoordinates are relat ive to the window which in this case is the if rame

Javascript

$(div)mousemove(function(e) var pageCoords = ( + epageX + + epageY + ) var cl ientCoords = ( + ecl ientX + + ecl ientY + ) $(spanfirst)text(( epageX epageY ) - + pageCoords) $(spanlast)text(( ecl ientX ecl ientY ) - + clientCoords) )

CSS

div width220px height170px margin10px margin-right50px backgroundyellow border2px groove floatright p margin0 margin-left10px colorred width220px height120px padding-top70px floatleft font-size14px span displayblock

HTML

ltpgt Try scroll ing too ltspangtMove the mouse over the divltspangt ltspangtampnbspltspangt ltpgt

ltdivgtltdivgt

hover

Bind two handlers to the matched elements to be executed when the mouse pointer entersand leaves the elements

Added in version 10

hover(handlerIn(eventObject) handlerOut(eventObject))jQuery

handlerIn(eventObject)Funct ion A funct ion to execute when the mouse pointerenters the element

handlerOut(eventObject)Funct ion A funct ion to execute when the mouse pointerleaves the element

The hover() method binds handlers for both mouseenter and mouseleave events You can useit to simply apply behavior to an element during the t ime the mouse is within the element

Calling $(selector)hover(handlerIn handlerOut) is shorthand for

$(selector)mouseenter(handlerIn)mouseleave(handlerOut)

See the discussions for mouseenter() and mouseleave() for more details

Example 1 To add a special style to list items that are being hovered over t ry

Javascript

$(l i)hover( function () $(this)append($(ltspangt ltspangt)) function () $(this)find(spanlast)remove() )

l i with fade class$(l i fade)hover(function()$(this)fadeOut(100)$(this)fadeIn(500))

CSS

ul margin-left20px colorblue l i cursordefault span colorred

HTML

ltulgt ltligtMilkltligt ltligtBreadltligt ltli class=fadegtChipsltligt

ltli class=fadegtSocksltligt ltulgt

Example 2 To add a special style to table cells that are being hovered over t ry

Javascript

$(td)hover( function () $(this)addClass(hover) function () $(this)removeClass(hover) )

Example 3 To unbind the above example use

Javascript

$(td)unbind(mouseenter mouseleave)

hover

Bind a single handler to the matched elements to be executed when the mouse pointer entersor leaves the elements

Added in version 14

hover(handlerInOut(eventObject))jQuery

handlerInOut(eventObject)Funct ion A funct ion to execute when the mouse pointerenters or leaves the element

The hover() method when passed a single funct ion will execute that handler for bothmouseenter and mouseleave events This allows the user to use jQuerys various togglemethods within the handler or to respond dif ferent ly within the handler depending on theeventtype

Calling $(selector)hover(handlerInOut) is shorthand for

$(selector)bind(mouseenter mouseleave handlerInOut)

See the discussions for mouseenter() and mouseleave() for more details

Example 1 Slide the next sibling LI up or down on hover and toggle a class

Javascript

$(l i)fi lter(odd)hide() end()fi lter(even)hover( function () $(this)toggleClass(active) next()stop(true true)sl ideToggle() )

CSS

ul margin-left20px colorblue l i cursordefault l i active backgroundblackcolorwhite span colorred

HTML

ltulgt ltligtMilkltligt ltligtWhiteltligt ltligtCarrotsltligt ltligtOrangeltligt ltligtBroccoliltl igt ltligtGreenltligt ltulgt

mouseleave

Bind an event handler to be f ired when the mouse leaves an element or t rigger that handler onan element

Added in version 10

mouseleave()jQuery

This method is a shortcut for bind(mouseleave handler) in the f irst two variat ions andtrigger(mouseleave) in the third

The mouseleave JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer leaves the element Any HTML elementcan receive this event

For example consider the HTML

ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The event handler can be boundto any element

$(outer)mouseleave(function() $(log)append(ltdivgtHandler for mouseleave() calledltdivgt))

Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

$(other)cl ick(function() $(outer)mouseleave())

After this code executes clicks on Trigger the handler will also append the message

The mouseleave event dif fers f rom mouseout in the way it handles event bubbling If mouseoutwere used in this example then when the mouse pointer moved out of the Inner element thehandler would be triggered This is usually undesirable behavior The mouseleave event on theother hand only t riggers its handler when the mouse leaves the element it is bound to not adescendant So in this example the handler is t riggered when the mouse leaves the Outerelement but not the Inner element

Example 1 Show number of t imes mouseout and mouseleave events are t riggered mouseoutf ires when the pointer moves out of child element as well while mouseleave f ires only when thepointer moves out of the bound element

CSS

divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

Javascript

var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) )mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )

var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) )mouseleave(function() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

HTML

ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

mouseenter

Bind an event handler to be f ired when the mouse enters an element or t rigger that handler onan element

Added in version 10

mouseenter()jQuery

This method is a shortcut for bind(mouseenter handler) in the f irst two variat ions andtrigger(mouseenter) in the third

The mouseenter JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer enters the element Any HTML elementcan receive this event

For example consider the HTML

ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The event handler can be boundto any element

$(outer)mouseenter(function() $(log)append(ltdivgtHandler for mouseenter() calledltdivgt))

Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

$(other)cl ick(function() $(outer)mouseenter())

After this code executes clicks on Trigger the handler will also append the message

The mouseenter event dif fers f rom mouseover in the way it handles event bubbling Ifmouseover were used in this example then when the mouse pointer moved over the Innerelement the handler would be triggered This is usually undesirable behavior The mouseenterevent on the other hand only t riggers its handler when the mouse enters the element it isbound to not a descendant So in this example the handler is t riggered when the mouse entersthe Outer element but not the Inner element

Example 1 Show texts when mouseenter and mouseout event t riggering mouseover f ireswhen the pointer moves into the child element as well while mouseenter f ires only when thepointer moves into the bound element

CSS

divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

Javascript

var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) $(plastthis)text(++i) )mouseout(function() $(pfirstthis)text(mouse out) )

var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) $(plastthis)text(++n) )mouseleave(function() $(pfirstthis)text(mouse leave) )

HTML

ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

mouseout

Bind an event handler to the mouseout JavaScript event or t rigger that event on an element

Added in version 10

mouseout()jQuery

This method is a shortcut for bind(mouseout handler) in the f irst two variat ion andtrigger(mouseout ) in the third

The mouseout event is sent to an element when the mouse pointer leaves the element AnyHTML element can receive this event

For example consider the HTML

ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The event handler can be boundto any element

$(outer)mouseout(function() $(log)append(Handler for mouseout() called))

Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt To trigger the event manually apply mouseout() without an argument

$(other)cl ick(function() $(outer)mouseout())

After this code executes clicks on Trigger the handler will also append the message

This event type can cause many headaches due to event bubbling For instance when themouse pointer moves out of the Inner element in this example a mouseout event will be sentto that then trickle up to Outer This can trigger the bound mouseout handler at inopportunet imes See the discussion for mouseleave() for a useful alternat ive

Example 1 Show the number of t imes mouseout and mouseleave events are t riggeredmouseout f ires when the pointer moves out of the child element as well while mouseleave f iresonly when the pointer moves out of the bound element

CSS

divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

Javascript

var i = 0 $(divoverout)mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )mouseover(function() $(pfirstthis)text(mouse over) )

var n = 0 $(diventerleave)bind(mouseenterfunction() $(pfirstthis)text(mouse enter) )bind(mouseleavefunction() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

HTML

ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

mouseover

Bind an event handler to the mouseover JavaScript event or t rigger that event on anelement

Added in version 10

mouseover()jQuery

This method is a shortcut for bind(mouseover handler) in the f irst two variat ions andtrigger(mouseover) in the third

The mouseover event is sent to an element when the mouse pointer enters the element AnyHTML element can receive this event

For example consider the HTML

ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

The event handler can be boundto any element

$(outer)mouseover(function() $(log)append(ltdivgtHandler for mouseover() calledltdivgt))

Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt We can also t rigger the event when another element is clicked

$(other)cl ick(function() $(outer)mouseover())

After this code executes clicks on Trigger the handler will also append the message

This event type can cause many headaches due to event bubbling For instance when themouse pointer moves over the Inner element in this example a mouseover event will be sent tothat then trickle up to Outer This can trigger our bound mouseover handler at inopportunet imes See the discussion for mouseenter() for a useful alternat ive

Example 1 Show the number of t imes mouseover and mouseenter events are t riggeredmouseover f ires when the pointer moves into the child element as well while mouseenter f iresonly when the pointer moves into the bound element

CSS

divout width40 height120px margin0 15px background-colorD6EDFC floatleft divin width60 height60 background-colorFFCC00 margin10px auto p l ine-height1em margin0 padding0

Javascript

var i = 0 $(divoverout)mouseover(function() i += 1 $(this)find(span)text( mouse over x + i ) )mouseout(function() $(this)find(span)text(mouse out ) )

var n = 0 $(diventerleave)mouseenter(function() n += 1 $(this)find(span)text( mouse enter x + n ) )mouseleave(function() $(this)find(span)text(mouse leave) )

HTML

ltdiv class=out overoutgt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

ltdiv class=out enterleavegt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

dblclick

Bind an event handler to the dblclick JavaScript event or t rigger that event on an element

Added in version 10

dblclick()jQuery

This method is a shortcut for bind(dblclick handler) in the f irst two variat ions andtrigger(dblclick) in the third The dblclick event is sent to an element when the element isdouble-clicked Any HTML element can receive this event For example consider the HTML

ltdiv id=targetgt Double-click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be boundto any ltdivgt

$(target)dblcl ick(function() alert(Handler for dblcl ick() called))

Now double-clicking on this element displays the alert

Handler for dblclick() called

To trigger the event manually apply dblclick() without an argument

$(other)cl ick(function() $(target)dblcl ick())

After this code executes (single) clicks on Trigger the handler will also alert the message

The dblclick event is only t riggered af ter this exact series of events

The mouse button is depressed while the pointer is inside the element

The mouse button is released while the pointer is inside the element

The mouse button is depressed again while the pointer is inside the element within at ime window that is system-dependent

The mouse button is released while the pointer is inside the element

It is inadvisable to bind handlers to both the click and dblclick events for the same element Thesequence of events t riggered varies f rom browser to browser with some receiving two clickevents before the dblclick and others only one Double-click sensit ivity (maximum t ime betweenclicks that is detected as a double click) can vary by operat ing system and browser and is of tenuser-conf igurable

Example 1 To bind a Hello World alert box the dblclick event on every paragraph on the page

Javascript

$(p)dblcl ick( function () alert(Hello World) )

Example 2 Double click to toggle background color

Javascript

var divdbl = $(divfirst) divdbldblcl ick(function () divdbltoggleClass(dbl) )

CSS

div backgroundblue colorwhite height100px width150px divdbl backgroundyellowcolorblack

HTML

ltdivgtltdivgtltspangtDouble cl ick the blockltspangt

click

Bind an event handler to the click JavaScript event or t rigger that event on an element

Added in version 10

click()jQuery

This method is a shortcut for bind(click handler) in the f irst two variat ions and t rigger(click)in the third

The click event is sent to an element when the mouse pointer is over the element and themouse button is pressed and released Any HTML element can receive this event

For example consider the HTMLltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be boundto any ltdivgt

$(target)cl ick(function() alert(Handler for cl ick() called))

Now if we click on this element the alert is displayed

Handler for click() called

We can also t rigger the event when a dif ferent element is clicked

$(other)cl ick(function() $(target)cl ick())

After this code executes clicks on Trigger the handler will also alert the message

The click event is only t riggered af ter this exact series of events

The mouse button is depressed while the pointer is inside the element

The mouse button is released while the pointer is inside the element

This is usually the desired sequence before taking an act ion If this is not required themousedown or mouseup event may be more suitable

Example 1 To hide paragraphs on a page when they are clicked

Javascript

$(p)cl ick(function () $(this)sl ideUp() ) $(p)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

CSS

p colorred margin5px cursorpointer phil ite backgroundyellow

HTML

ltpgtFirst Paragraphltpgt

ltpgtSecond Paragraphltpgt ltpgtYet one more Paragraphltpgt

Example 2 To trigger the click event on all of the paragraphs on the page

Javascript

$(p)cl ick()

mouseup

Bind an event handler to the mouseup JavaScript event or t rigger that event on an element

Added in version 10

mouseup()jQuery

This method is a shortcut for bind(mouseup handler) in the f irst variat ion andtrigger(mouseup) in the second

The mouseup event is sent to an element when the mouse pointer is over the element and themouse button is released Any HTML element can receive this event

For example consider the HTML

ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be boundto any ltdivgt

$(target)mouseup(function() alert(Handler for mouseup() called))

Now if we click on this element the alert is displayed

Handler for mouseup() called

We can also t rigger the event when a dif ferent element is clicked

$(other)cl ick(function() $(target)mouseup())

After this code executes clicks on Trigger the handler will also alert the message

If the user clicks outside an element drags onto it and releases the button this is st ill countedas a mouseup event This sequence of act ions is not t reated as a button press in most userinterfaces so it is usually better to use the click event unless we know that the mouseup eventis preferable for a part icular situat ion

Example 1 Show texts when mouseup and mousedown event t riggering

Javascript

$(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

HTML

ltpgtPress mouse and release hereltpgt

mousedown

Bind an event handler to the mousedown JavaScript event or t rigger that event on anelement

Added in version 10

mousedown()jQuery

This method is a shortcut for bind(mousedown handler) in the f irst variat ion andtrigger(mousedown) in the second

The mousedown event is sent to an element when the mouse pointer is over the element andthe mouse button is pressed Any HTML element can receive this event

For example consider the HTML

ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

The event handler can be boundto any ltdivgt

$(target)mousedown(function() alert(Handler for mousedown() called))

Now if we click on this element the alert is displayed

Handler for mousedown() called

We can also t rigger the event when a dif ferent element is clicked

$(other)cl ick(function() $(target)mousedown())

After this code executes clicks on Trigger the handler will also alert the message

The mousedown event is sent when any mouse button is clicked To act only on specif icbuttons we can use the event object s which property Not all browsers support this property(Internet Explorer uses button instead) but jQuery normalizes the property so that it is safe touse in any browser The value of which will be 1 for the lef t but ton 2 for the middle button or 3for the right button

This event is primarily useful for ensuring that the primary button was used to begin a dragoperat ion if ignored strange results can occur when the user at tempts to use a context menuWhile the middle and right buttons can be detected with these propert ies this is not reliable InOpera 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 st ill countedas a mousedown event This sequence of act ions is t reated as a canceling of the buttonpress in most user interfaces so it is usually better to use the click event unless we know thatthe mousedown event is preferable for a part icular situat ion

Example 1 Show texts when mouseup and mousedown event t riggering

Javascript

$(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

HTML

ltpgtPress mouse and release hereltpgt

error

Bind an event handler to the error JavaScript event

Added in version 143

error(eventData handler(eventObject))jQuery

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

This method is a shortcut for bind(error handler)

The error event is sent to elements such as images that are referenced by a document andloaded by the browser It is called if the element was not loaded correct ly

For example consider a page with a simple image element

ltimg alt=Book id=book gt

The event handler can be bound to the image

$(book) error(function() alert(Handler for error() called) ) attr(src missingpng)

If the image cannot be loaded (for example because it is not present at the supplied URL) thealert is displayed

Handler for error() called

The event handler must be attached before the browser fires the error eventwhich is why the example sets the src attribute after attaching the handler Alsothe error event may not be correctly fired when the page is served locally errorrelies on HTTP status codes and will generally not be triggered if the URL usesthe file protocol

Note A jQuery error event handler should not be at tached to the window object The browserf ires the windows error event when a script error occurs However the window error eventreceives dif ferent arguments and has dif ferent return value requirements than convent ionalevent handlers Use windowonerror instead

Example 1 To hide the broken image icons for IE users you can try

Javascript

$(img) error(function() $(this)hide() ) attr(src missingpng)

unload

Bind an event handler to the unload JavaScript event

Added in version 143

unload(eventData handler(eventObject))jQuery

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

This method is a shortcut for bind(unload handler)

The unload event is sent to the window element when the user navigates away from the pageThis 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 t rigger the eventClosing the browser window will cause the event to be triggered Even a page reload will f irstcreate an unload event

The exact handling of the unload event has varied from version to version ofbrowsers For example some versions of Firefox trigger the event when a link isfollowed but not when the window is closed In practical usage behavior shouldbe tested on all supported browsers and contrasted with the proprietarybeforeunload event

Any unload event handler should be bound to the window object

$(window)unload(function() alert(Handler for unload() called))

After this code executes the alert will be displayed whenever the browser leaves the currentpage It is not possible to cancel the unload event with preventDefault () This event is availableso that scripts can perform cleanup when the user leaves the page

Example 1 To display an alert when a page is unloaded

Javascript

$(window)unload( function () alert(Bye now) )

load

Bind an event handler to the load JavaScript event

Added in version 143

load(eventData handler(eventObject))jQuery

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

This method is a shortcut for bind(load handler)

The load 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 f ramesif rames and the window object

For example consider a page with a simple image

ltimg src=bookpng alt=Book id=book gt

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 executedearlier it is usually best to place it in a handler sent to the ready() method

The Ajax module also has a method named load() Which one is fired dependson the set of arguments passed

Caveats of the load event when used with images

A common challenge developers attempt to solve using the load() shortcut is toexecute a function when an image (or collection of images) have completelyloaded There are several known caveats with this that should be noted Theseare

It doesnt work consistently nor reliably cross-browser

It doesnt fire correctly in WebKit if the image src is set to the same src asbefore

It doesnt correctly bubble up the DOM tree

Can cease to fire for images that already live in the browsers cache

Note The live() and delegate() methods cannot be used to detect the load eventof an iframe The load event does not correctly bubble up the parent documentand the eventtarget isnt set by Firefox IE9 or Chrome which is required to doevent delegation

Note When calling load() using a URL without a suffixed selector expression the

content is passed to html() prior to scripts being removed This executes the scriptblocks before they are discarded If load() is however called with a selectorexpression appended to the URL the scripts are stripped out prior to the DOMbeing updated which is why they are never executed An example of both casescan be seen below

Here any JavaScript loaded into a as a part of the document will successfully execute

$(a)load(articlehtml)

However in this case script blocks in the document being loaded into b are stripped out priorto being executed

$(b)load(articlehtml target)

Example 1 Run a funct ion when the page is fully loaded including graphics

Javascript

$(window)load(function () run code)

Example 2 Add the class bigImg to all images with height greater then 100 upon each imageload

Javascript

$( imguserIcon)load(function() if($(this)height() gt 100) $(this)addClass(bigImg) )

ready

Specify a funct ion to execute when the DOM is fully loaded

Added in version 10

ready(handler)jQuery

handlerFunct ion A funct ion to execute af ter the DOM is ready

While JavaScript provides the load event for execut ing code when a page is rendered thisevent does not get t riggered unt il all assets such as images have been completely received Inmost cases the script can be run as soon as the DOM hierarchy has been fully constructedThe handler passed to ready() is guaranteed to be executed af ter the DOM is ready so this isusually the best place to at tach all other event handlers and run other jQuery code When usingscripts that rely on the value of CSS style propert ies it s important to reference externalstylesheets or embed style elements before referencing the scripts

In cases where code relies on loaded assets (for example if the dimensions of an image arerequired) the code should be placed in a handler for the load event instead

The ready() method is generally incompatible with the ltbody onload=gtattribute If load must be used either do not use ready() or use jQuerys load()method to attach load event handlers to the window or to more specific items likeimages

All three of the following syntaxes are equivalent

$(document)ready(handler)

$()ready(handler) (this is not recommended)

$(handler)

There is also $(document)bind(ready handler) This behaves similarly to the ready methodbut with one except ion If the ready event has already f ired and you try to bind(ready) thebound handler will not be executed Ready handlers bound this way are executed after anybound by the other three methods above

The ready() method can only be called on a jQuery object matching the current document sothe selector can be omit ted

The ready() method is typically used with an anonymous funct ion

$(document)ready(function() Handler for ready() called)

Which is equivalent to calling

$(function() Handler for ready() called)

If ready() is called af ter the DOM has been init ialized the new handler passed in will beexecuted immediately

Aliasing the jQuery Namespace

When using another JavaScript library we may wish to call $noConf lict () to avoid namespacedif f icult ies When this funct ion is called the $ shortcut is no longer available forcing us to writejQuery each t ime we would normally write $ However the handler passed to the ready()method can take an argument which is passed the global jQuery object This means we canrename the object within the context of our ready() handler without af fect ing other code

jQuery(document)ready(function($) Code using $ as usual goes here)

Example 1 Display a message when the DOM is loaded

Javascript

$(document)ready(function () $(p)text(The DOM is now loaded and can be manipulated))

CSS

p colorred

HTML

ltpgtNot loaded yetltpgt

die

Remove all event handlers previously at tached using live() f rom the elements

Added in version 141

die()jQuery

Any handler that has been at tached with live() can be removed with die() This method isanalogous to calling unbind() with no arguments which is used to remove all handlers at tached

with bind() See the discussions of live() and unbind() for further details

Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

die

Remove an event handler previously at tached using live() f rom the elements

Added in version 143

die(eventTypes)jQuery

eventTypesMap A map of one or more event types such as click or keydown and theircorresponding funct ions that are no longer to be executed

Any handler that has been at tached with live() can be removed with die() This method isanalogous to unbind() which is used to remove handlers at tached with bind() See thediscussions of live() and unbind() for further details

Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

Example 1 Can bind and unbind events to the colored button

Javascript

function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(theone)l ive(click aClick) text(Can Click))$(unbind)cl ick(function () $(theone)die(click aClick) text(Does nothing))

CSS

button margin5px buttontheone colorred backgroundyellow

HTML

ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

ltdiv style=displaynonegtClickltdivgt

Example 2 To unbind all live events f rom all paragraphs write

Javascript

$(p)die()

Example 3 To unbind all live click events f rom all paragraphs write

Javascript

$(p)die( cl ick )

Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

Javascript

var foo = function () code to handle some kind of event

$(p)l ive(click foo) now foo wil l be called when paragraphs are cl icked

$(p)die(click foo) foo wil l no longer be called

live

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

Added in version 143

live(events)jQuery

eventsObject A map of one or more JavaScript event types and funct ions to executefor them

This method is a variat ion on the basic bind() method for at taching event handlers to elementsWhen bind() is called the elements that the jQuery object refers to get the handler at tachedelements that get introduced later do not so they would require another bind() call Forinstance consider the HTML

ltbodygt ltdiv class=clickmegt Click here ltdivgtltbodygt

To bind a simple click handler to this element

$(cl ickme)bind(cl ick function() Bound handler called)

When the element is clicked the handler is called However suppose that af ter this anotherelement is added

$(body)append(ltdiv class=clickmegtAnother targetltdivgt)

This new element also matches the selector clickme but since it was added af ter the call tobind() clicks on it will do nothing

The live() method provides an alternat ive to this behavior To bind a click handler to the targetelement using this method

$(cl ickme)l ive(cl ick function() Live handler called)

And then later add a new element

$(body)append(ltdiv class=clickmegtAnother targetltdivgt)

Then clicks on the new element will also t rigger the handler

To unbind the click handlers f rom all ltdiv class=clickmegt that were bound using live() use thedie() method

$(cl ickme)die(click)

Event Delegation

The live() method is able to af fect elements that have not yet been added to the DOM throughthe use of event delegat ion a handler bound to an ancestor element is responsible for eventsthat are t riggered on its descendants The handler passed to live() is never bound to anelement instead live() binds a special handler to the root of the DOM tree In the exampleabove when the new element is clicked the following steps occur

1 A click event is generated and passed to the ltdivgt for handling

2 No handler is direct ly bound to the ltdivgt so the event bubbles up the DOM tree

3 The event bubbles up unt il it reaches the root of the t ree which is where live() binds itsspecial handlers by default

As of jQuery 14 event bubbling can optionally stop at a DOM element context

4 The special click handler bound by live() executes

5 This handler tests the target of the event object to see whether it should cont inue Thistest is performed by checking if $(eventtarget)closest(clickme) is able to locate amatching element

6 If a matching element is found the original handler is called on it

Because the test in step 5 is not performed unt il the event occurs elements can be added atany t ime and st ill respond to events

See the discussion for bind() for more informat ion on event binding

Multiple Events

As of jQuery 141 live() can accept mult iple space-separated events similar to thefunct ionality provided in bind() For example you can live bind the mouseover and mouseoutevents at the same t ime like so

$(hoverme)l ive(mouseover mouseout function(event) if ( eventtype == mouseover ) do something on mouseover else do something on mouseout )

As of jQuery 143 you can bind mult iple live event handlers simultaneously by passing a map ofevent typehandler pairs

$(a)l ive( cl ick function() do something on click mouseover function() do something on mouseover )

Event Data

As of jQuery 14 the opt ional eventData parameter is available for passing addit ionalinformat ion to the handler One handy use of this parameter is to work around issues causedby closures See the bind() methods Passing Event Data discussion for more informat ion

Event Context

As of jQuery 14 live events can be bound to a DOM element context rather than to thedefault document root To set this context use the jQuery() funct ions second argumentpassing in a single DOM element (as opposed to a jQuery collect ion or a selector)

$(divcl ickme $(container)[0])l ive(click function() Live handler called)

The live handler in this example is called only when ltdiv class=clickmegt is a descendant of anelement with an ID of container

Caveats

The live() technique is useful but due to its special approach cannot be simply subst ituted forbind() in all cases Specif ic dif ferences include

DOM traversal methods are not supported for f inding elements to send to live()Rather the live() method should always be called direct ly af ter a selector as in theexample above

To stop further handlers f rom execut ing af ter one bound using live() the handler mustreturn false Calling stopPropagat ion() will not accomplish this

The paste and reset events in addit ion to change when used with inputs of type f ileare not fully supported by the live() method due to issues with simulat ing event bubblingin Internet Explorer In these cases the bind() method can be used instead

In jQuery 13x only the following JavaScript events (in addit ion to custom events)could be bound with live() click dblclick keydown keypress keyup mousedown

mousemove mouseout mouseover and mouseup

As of jQuery 14 the live() method supports custom events as well as allJavaScript events that bubble

As of jQuery 141 even focus and blur work with live (mapping to themore appropriate bubbling events focusin and focusout)

As of jQuery 141 the hover event can be specified (mapping tomouseenter and mouseleave which in turn are mapped to mouseover andmouseout)

Example 1 Click a paragraph to add another Note that live() binds the click event to allparagraphs - even new ones

Javascript

$(p)l ive(click function() $(this)after(ltpgtAnother paragraphltpgt))

CSS

p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

HTML

ltpgtClick meltpgt

ltspangtltspangt

Example 2 Cancel a default act ion and prevent it f rom bubbling up by returning false

Javascript

$(a)l ive(click function() return false )

Example 3 Cancel only the default act ion by using the preventDefault method

Javascript

$(a)l ive(click function(event) eventpreventDefault())

Example 4 Bind custom events with live()

Javascript

$(p)l ive(myCustomEvent function(e myName myValue) $(this)text(Hi there) $(span)stop()css(opacity 1) text(myName = + myName) fadeIn(30)fadeOut(1000))$(button)cl ick(function () $(p)trigger(myCustomEvent))

CSS

p colorred span colorblue

HTML

ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

Example 5 Use a map to bind mult iple live event handlers Note that live() binds the clickmouseover and mouseout events to all paragraphs acirceurordquo even new ones

Javascript

$(p)l ive( cl ick function() $(this)after(ltpgtAnother paragraphltpgt) mouseover function() $(this)addClass(over) mouseout function() $(this)removeClass(over) )

CSS

p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

HTML

ltpgtClick meltpgt ltspangtltspangt

triggerHandler

Execute all handlers at tached to an element for an event

Added in version 12

triggerHandler(eventType extraParameters)Object

eventTypeString A string containing a JavaScript event type such as click orsubmit

extraParametersArray An array of addit ional parameters to pass along to the eventhandler

The t riggerHandler() method behaves similarly to t rigger() with the following except ions

The t riggerHandler() method does not cause the default behavior of an event to occur(such as a form submission)

While t rigger() will operate on all elements matched by the jQuery object t riggerHandler() only af fects the f irst matched element

Events created with t riggerHandler() do not bubble up the DOM hierarchy if they arenot handled by the target element direct ly they do nothing

Instead of returning the jQuery object (to allow chaining) t riggerHandler() returnswhatever value was returned by the last handler it caused to be executed If no handlersare t riggered it returns undef ined

For more informat ion on this method see the discussion for t rigger()

Example 1 If you called t riggerHandler() on a focus event - the browsers default focus act ionwould not be triggered only the event handlers bound to the focus event

Javascript

$(old)cl ick(function()$(input)trigger(focus))$(new)cl ick(function()$(input)triggerHandler(focus))$(input)focus(function()$(ltspangtFocusedltspangt)appendTo(body)fadeOut(1000))

HTML

ltbutton id=oldgttrigger(focus)ltbuttongtltbutton id=newgttriggerHandler(focus)ltbuttongtltbrgtltbrgt

ltinput type=text value=To Be Focusedgt

trigger

Execute all handlers and behaviors at tached to the matched elements for the given event type

Added in version 13

trigger(event)jQuery

eventEvent A jQueryEvent object

Any event handlers at tached with bind() or one of its shortcut methods are t riggered when thecorresponding event occurs They can be f ired manually however with the t rigger() method Acall to t rigger() executes the handlers in the same order they would be if the event weretriggered naturally by the user

$(foo)bind(cl ick function() alert($(this)text()) ) $(foo)trigger(cl ick)

As of jQuery 13 t rigger()ed events bubble up the DOM tree an event handler can stop thebubbling by returning false f rom the handler or calling the stopPropagat ion() method on theevent object passed into the event Although t rigger() simulates an event act ivat ion completewith a synthesized event object it does not perfect ly replicate a naturally-occurring event

To trigger handlers bound via jQuery without also t riggering the nat ive event use

t riggerHandler() instead

When we def ine a custom event type using the bind() method the second argument tot rigger() can become useful For example suppose we have bound a handler for the customevent to our element instead of the built -in click 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 f irst parameter to an event handler but if addit ionalparameters are specif ied during a t rigger() call these parameters will be passed along to thehandler as well To pass more than one parameter use an array as shown here As of jQuery162 a single parameter can be passed without using an array

Note the dif ference between the extra parameters were passing here and the eventDataparameter to the bind() method Both are mechanisms for passing informat ion to an eventhandler but the extraParameters argument to t rigger() allows informat ion to be determined atthe t ime the event is t riggered while the eventData argument to bind() requires the informat ionto be already computed at the t ime the handler is bound

Example 1 Clicks to button 2 also t rigger a click for button 1

Javascript

$(buttonfirst)cl ick(function () update($(spanfirst)))$(buttonlast)cl ick(function () $(buttonfirst)trigger(cl ick)

update($(spanlast)))

function update(j) var n = parseInt(jtext() 10)j text(n + 1)

CSS

button margin10px div colorblue font-weightbold span colorred

HTML

ltbuttongtButton 1ltbuttongtltbuttongtButton 2ltbuttongtltdivgtltspangt0ltspangt button 1 clicksltdivgt

ltdivgtltspangt0ltspangt button 2 clicksltdivgt

Example 2 To submit the f irst form without using the submit() funct ion t ry

Javascript

$(formfirst)trigger(submit)

Example 3 To submit the f irst form without using the submit() funct ion t ry

Javascript

var event = jQueryEvent(submit)$(formfirst)trigger(event)if ( eventisDefaultPrevented() ) Perform an action

Example 4 To pass arbit rary data to an event

Javascript

$(p)cl ick( function (event a b) when a normal cl ick fires a and b are undefined for a trigger l ike below a refers to foo and b refers to bar

)trigger(click [foo bar])

Example 5 To pass arbit rary data through an event object

Javascript

var event = jQueryEvent(logged)eventuser = fooeventpass = bar$(body)trigger(event)

Example 6 Alternat ive way to pass data through an event object

Javascript

$(body)trigger(typeloggeduserfoopassbar

)

one

Attach a handler to an event for the elements The handler is executed at most once perelement

Added in version 11

one(eventType eventData handler(eventObject))jQuery

eventTypeString A string containing one or more JavaScript event typessuch as click or submit or custom event names

eventDataObject (opt ional) A map of data that will be passed to theevent handler

handler(eventObject)Funct ion A funct ion to execute at the t ime the event is t riggered

This method is ident ical to bind() except that the handler is unbound af ter its f irst invocat ionFor example

$(foo)one(click function() alert(This wil l be displayed only once))

After the code is executed a click on the element with ID foo will display the alert Subsequentclicks will do nothing This code is equivalent to

$(foo)bind(click function( event ) alert(This wil l be displayed only once) $(this)unbind( event ))

In other words explicit ly calling unbind() f rom within a regularly-bound handler has exact ly thesame effect

If the f irst argument contains more than one space-separated event types the event handler is

called once for each event type

Example 1 Tie a one-t ime click to each div

Javascript

var n = 0$(div)one(click function() var index = $(div)index(this) $(this)css( borderStyleinset cursorauto ) $(p)text(Div at index + index + cl icked + Thats + ++n + total cl icks))

CSS

div width60px height60px margin5px floatleftbackgroundgreen border10px outset cursorpointer p colorred margin0 clearleft

HTML

ltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

ltpgtClick a green squareltpgt

Example 2 To display the text of all paragraphs in an alert box the f irst t ime each of them isclicked

Javascript

$(p)one(click function()alert( $(this)text() ))

unbind

Remove a previously-at tached event handler f rom the elements

Added in version 10

unbind(event)jQuery

eventObject A JavaScript event object as passed to an event handler

Any handler that has been at tached with bind() can be removed with unbind() In the simplestcase with no arguments unbind() removes all handlers at tached to the elements

$(foo)unbind()

This version removes the handlers regardless of type To be more precise we can pass anevent type

$(foo)unbind(cl ick)

By specifying the click event type only handlers for that event type will be unbound Thisapproach can st ill have negat ive ramif icat ions if other scripts might be at taching behaviors tothe same element however Robust and extensible applicat ions typically demand the two-argument version for this reason

var handler = function() alert(The quick brown fox jumps over the lazy dog)$(foo)bind(cl ick handler)$(foo)unbind(cl ick handler)

By naming the handler we can be assured that no other funct ions are caught in the crossf ireNote that the following will not work

$(foo)bind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

wil l NOT work$(foo)unbind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

Even though the two funct ions are ident ical in content they are created separately and soJavaScript is f ree to keep them as dist inct funct ion objects To unbind a part icular handler weneed a reference to that funct ion and not a dif ferent one that happens to do the same thing

Note Because the live() method binds event handlers to document by defaultcalling unbind() on document will unbind the handlers bound by live() as wellFor example $(document)unbind(click) will remove not only$(document)bind(click fn1)

but also

$(afoo)live(click fn2)

Note Using a proxied function to unbind an event on an element will unbind allproxied functions on that element as the same proxy function is used for allproxied events To allow unbinding a specific event use unique class names onthe event (eg clickproxy1 clickproxy2) when attaching them

Using Namespaces

Instead of maintaining references to handlers in order to unbind them we can namespace theevents and use this capability to narrow the scope of our unbinding act ions As shown in thediscussion for the bind() method namespaces are def ined by using a period () character whenbinding a handler

$(foo)bind(cl ickmyEvents handler)

When a handler is bound in this fashion we can st ill unbind it the normal way

$(foo)unbind(cl ick)

However if we want to avoid af fect ing other handlers we can be more specif ic

$(foo)unbind(cl ickmyEvents)

We can also unbind all of the handlers in a namespace regardless of event type

$(foo)unbind(myEvents)

It is part icularly useful to at tach namespaces to event bindings when we are developing plug-insor otherwise writ ing code that may interact with other event-handling code in the future

Using the Event Object

The third form of the unbind() method is used when we wish to unbind a handler f rom withinitself For example suppose we wish to t rigger an event handler only three t imes

var timesClicked = 0$(foo)bind(cl ick function(event) alert(The quick brown fox jumps over the lazy dog) timesClicked++ if (timesClicked gt= 3) $(this)unbind(event) )

The handler in this case must take a parameter so that we can capture the event object anduse it to unbind the handler af ter the third click The event object contains the contextnecessary for unbind() to know which handler to remove This example is also an illustrat ion ofa closure Since the handler refers to the t imesClicked variable which is def ined outside thefunct ion increment ing the variable has an ef fect even between invocat ions of the handler

Example 1 Can bind and unbind events to the colored button

Javascript

function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () could use bind(cl ick aClick) instead but for variety$(theone)cl ick(aClick) text(Can Click))$(unbind)cl ick(function () $(theone)unbind(cl ick aClick) text(Does nothing))

CSS

button margin5px buttontheone colorred backgroundyellow

HTML

ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

ltdiv style=displaynonegtClickltdivgt

Example 2 To unbind all events f rom all paragraphs write

Javascript

$(p)unbind()

Example 3 To unbind all click events f rom all paragraphs write

Javascript

$(p)unbind( cl ick )

Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

Javascript

var foo = function () code to handle some kind of event

$(p)bind(click foo) now foo wil l be called when paragraphs are cl icked

$(p)unbind(click foo) foo wil l no longer be called

bind

Attach a handler to an event for the elements

Added in version 14

bind(events)jQuery

eventsObject A map of one or more JavaScript event types and funct ions to executefor them

The bind() method is the primary means of at taching behavior to a document All JavaScriptevent types such as focus mouseover and resize are allowed for eventType The error eventon the window object uses nonstandard convent ions and is not supported by jQuery at tach ahandler direct ly to the window object instead The beforeunload event is supported cross-browser in jQuery 151 and 16+ but is not supported in IE for jQuery 152 due to a regression

The jQuery library provides shortcut methods for binding the standard event types such asclick() for bind(click) A descript ion of each can be found in the discussion of its shortcutmethod blur focus focusin focusout load resize scroll unload click dblclick mousedownmouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error

Any string is legal for eventType if the string is not the name of a nat ive JavaScript event thenthe handler is bound to a custom event These events are never called by the browser but maybe triggered manually f rom other JavaScript code using t rigger() or t riggerHandler()

If the eventType string contains a period () character then the event is namespaced Theperiod character separates the event f rom its namespace For example in the callbind(clickname handler) the string click is the event type and the string name is thenamespace Namespacing allows us to unbind or t rigger some events of a type withoutaf fect ing others See the discussion of unbind() for more informat ion

When an event reaches an element all handlers bound to that event type for the element aref ired If there are mult iple handlers registered they will always execute in the order in which theywere bound After all handlers have executed the event cont inues along the normal eventpropagat ion path

A basic usage of bind() is

$(foo)bind(cl ick function() alert(User cl icked on foo))

This code will cause the element with an ID of foo to respond to the click event When a userclicks inside this element thereafter the alert will be shown

Multiple Events

Mult iple event types can be bound at once by including each one separated by a space

$(foo)bind(mouseenter mouseleave function() $(this)toggleClass(entered))

The ef fect of this on ltdiv id=foogt (when it does not init ially have the entered class) is toadd the entered class when the mouse enters the ltdivgt and remove the class when themouse leaves

As of jQuery 14 we can bind mult iple event handlers simultaneously by passing a map of eventtypehandler pairs

$(foo)bind( cl ick function() do something on click mouseenter function() do something on mouseenter )

Event Handlers

The handler parameter takes a callback funct ion as shown above Within the handler thekeyword this refers to the DOM element to which the handler is bound To make use of theelement in jQuery it can be passed to the normal $() funct ion For example

$(foo)bind(cl ick function() alert($(this)text()))

After this code is executed when the user clicks inside the element with an ID of foo its textcontents will be shown as an alert

As of jQuery 142 duplicate event handlers can be bound to an element instead of beingdiscarded For example

function test() alert(Hello) $(button)cl ick( test )$(button)cl ick( test )

The above will generate two alerts when the button is clicked

In jQuery 143 you can now pass in false in place of an event handler This will bind an eventhandler that s equivalent to funct ion() return false This funct ion can be removed at a latert ime by calling unbind( eventName false )

The Event object

The handler callback funct ion can also take parameters When the funct ion is called theJavaScript event object will be passed to the f irst parameter

The event object is of ten unnecessary and the parameter omit ted as suff icient context isusually available when the handler is bound to know exact ly what needs to be done when thehandler is t riggered However at t imes it becomes necessary to gather more informat ion aboutthe users environment at the t ime the event was init iated View the full Event Object

Returning false f rom a handler is equivalent to calling both preventDefault () andstopPropagat ion() on the event object

Using the event object in a handler looks like this

$(document)ready(function() $(foo)bind(cl ick function(event) alert(The mouse cursor is at ( + eventpageX + + eventpageY + )) ))

Note the parameter added to the anonymous funct ion This code will cause a click on theelement with ID foo to report the page coordinates of the mouse cursor at the t ime of the click

Passing Event Data

The opt ional eventData parameter is not commonly used When provided this argument allowsus to pass addit ional informat ion to the handler One handy use of this parameter is to workaround issues caused by closures For example suppose we have two event handlers that bothrefer to the same external variable

var message = Spoon$(foo)bind(cl ick function() alert(message))message = Not in the face$(bar)bind(cl ick function() alert(message))

Because the handlers are closures that both have message in their environment both willdisplay the message Not in the face when triggered The variables value has changed Tosidestep this we can pass the message in using eventData

var message = Spoon$(foo)bind(cl ick msg message function(event) alert(eventdatamsg))message = Not in the face$(bar)bind(cl ick msg message function(event) alert(eventdatamsg))

This t ime the variable is not referred to direct ly within the handlers instead the variable is

passed in by value through eventData which f ixes the value at the t ime the event is boundThe f irst handler will now display Spoon while the second will alert Not in the face

Note that objects are passed to functions by reference which further complicatesthis scenario

If eventData is present it is the second argument to the bind() method if no addit ional dataneeds to be sent to the handler then the callback is passed as the second and f inal argument

See the trigger() method reference for a way to pass data to a handler at the timethe event happens rather than when the handler is bound

As of jQuery 14 we can no longer at tach data (and thus events) to object embed or appletelements because crit ical errors occur when at taching data to Java applets

Note Although demonstrated in the next example it is inadvisable to bind handlers to both theclick and dblclick events for the same element The sequence of events t riggered varies f rombrowser to browser with some receiving two click events before the dblclick and others onlyone Double-click sensit ivity (maximum t ime between clicks that is detected as a double click)can vary by operat ing system and browser and is of ten user-conf igurable

Example 1 Handle click and double-click for the paragraph Note the coordinates are windowrelat ive so in this case relat ive to the demo if rame

Javascript

$(p)bind(click function(event)var str = ( + eventpageX + + eventpageY + )$(span)text(Click happened + str))$(p)bind(dblcl ick function()$(span)text(Double-click happened in + thisnodeName))$(p)bind(mouseenter mouseleave function(event)$(this)toggleClass(over))

CSS

p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

HTML

ltpgtClick or double cl ick hereltpgtltspangtltspangt

Example 2 To display each paragraphs text in an alert box whenever it is clicked

Javascript

$(p)bind(click function()alert( $(this)text() ))

Example 3 You can pass some extra data before the event handler

Javascript

function handler(event) alert(eventdatafoo)$(p)bind(click foo bar handler)

Example 4 Cancel a default act ion and prevent it f rom bubbling up by returning false

Javascript

$(form)bind(submit function() return false )

Example 5 Cancel only the default act ion by using the preventDefault () method

Javascript

$(form)bind(submit function(event) eventpreventDefault())

Example 6 Stop an event f rom bubbling without prevent ing the default act ion by using thestopPropagat ion() method

Javascript

$(form)bind(submit function(event) eventstopPropagation())

Example 7 Bind custom events

Javascript

$(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)cl ick(function () $(p)trigger(myCustomEvent [ John ]))

CSS

p colorred span colorblue

HTML

ltpgtHas an attached custom eventltpgtltbuttongtTrigger custom eventltbuttongtltspan style=displaynonegtltspangt

Example 8 Bind mult iple events simultaneously

Javascript

$(divtest)bind( cl ick function() $(this)addClass(active) mouseenter function() $(this)addClass(inside) mouseleave function() $(this)removeClass(inside) )

Deferred Object

deferredpipe

Utility method to f ilter andor chain Deferreds

Added in version 16

deferredpipe(doneFilter failFilter)Promise

doneFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isresolved

failFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isrejected

The deferredpipe() method returns a new promise that f ilters the status and values of adeferred through a funct ion The doneFilter and failFilter funct ions f ilter the original deferredsresolved rejected status and values These f ilter funct ions can return a new value to bepassed along to the piped promises done() or fail() callbacks or they can return anotherobservable object (Deferred Promise etc) which will pass its resolved rejected status andvalues to the piped promises callbacks If the f ilter funct ion used is null or not specif ied thepiped promise will be resolved or rejected with the same values as the original

Example 1 Filter resolve value

Javascript

var defer = $Deferred() fi ltered = deferpipe(function( value ) return value 2 )

deferresolve( 5 )fi ltereddone(function( value ) alert( Value is ( 25 = ) 10 + value ))

Example 2 Filter reject value

Javascript

var defer = $Deferred() fi ltered = deferpipe( null function( value ) return value 3 )

deferreject( 6 )fi lteredfail(function( value ) alert( Value is ( 36 = ) 18 + value ))

Example 3 Chain tasks

Javascript

var request = $ajax( url dataType json ) chained = requestpipe(function( data ) return $ajax( url2 data user datauserId ) )

chaineddone(function( data ) data retrieved from url2 as provided by the first request)

deferredalways

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

Added in version 16

deferredalways(alwaysCallbacks)Deferred

alwaysCallbacksFunct ion A funct ion or array of funct ions that is called when theDeferred is resolved or rejected

The argument can be either a single funct ion or an array of funct ions When the Deferred isresolved or rejected the alwaysCallbacks are called Since deferredalways() returns theDeferred object other methods of the Deferred object can be chained to this one includingaddit ional always() methods When the Deferred is resolved or rejected callbacks are executedin the order they were added using the arguments provided to the resolve reject resolveWithor rejectWith method calls For more informat ion see the documentat ion for Deferred object

Example 1 Since the jQueryget() method returns a jqXHR object which is derived from aDeferred object we can at tach a callback for both success and error using thedeferredalways() method

Javascript

$get(testphp)always( function() alert($get completed with success or error callback arguments) )

promise

Return a Promise object to observe when all act ions of a certain type bound to the collect ionqueued or not have f inished

Added in version 16

promise(type target)Promise

typeString (opt ional) The type of queue that needs to be observed

targetObject (opt ional) Object onto which the promise methods have to be at tached

The promise() method returns a dynamically generated Promise that is resolved once allact ions of a certain type bound to the collect ion queued or not have ended

By default type is fx which means the returned Promise is resolved when all animat ions ofthe selected elements have completed

Resolve context and sole argument is the collect ion onto which promise() has been called

If target is provided promise() will at tach the methods onto it and then return this object ratherthan create a new one This can be useful to at tach the Promise behavior to an object thatalready exists

Note The returned Promise is linked to a Deferred object stored on the data() foran element Since the remove() method removes the elements data as well asthe element itself it will prevent any of the elements unresolved Promises fromresolving If it is necessary to remove an element from the DOM before its Promiseis resolved use detach() instead and follow with removeData() after resolution

Example 1 Using promise() on a collect ion with no act ive animat ion returns a resolved Promise

Javascript

var div = $( ltdiv gt )

divpromise()done(function( arg1 ) wil l fire right away and alert true alert( this === div ampamp arg1 === div ))

Example 2 Resolve the returned Promise when all animat ions have ended (including thoseinit iated in the animat ion callback or added later on)

CSS

div height 50px width 50px float left margin-right 10px display none background-color 090

HTML

ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

Javascript

$(button)bind( cl ick function() $(p)append( Started) $(div)each(function( i ) $( this )fadeIn()fadeOut( 1000 (i+1) ) )

$( div )promise()done(function() $( p )append( Finished ) ))

Example 3 Resolve the returned Promise using a $when() statement (the promise() methodmakes it possible to do this with jQuery collect ions)

CSS

div height 50px width 50px float left margin-right 10px display none background-color 090

HTML

ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

Javascript

var effect = function() return $(div)fadeIn(800)delay(1200)fadeOut()

$(button)bind( cl ick function() $(p)append( Started )

$when( effect() )done(function() $(p)append( Finished ) ))

deferredpromise

Return a Deferreds Promise object

Added in version 15

deferredpromise(target)Promise

targetObject (opt ional) Object onto which the promise methods have to be at tached

The deferredpromise() method allows an asynchronous funct ion to prevent other code frominterfering with the progress or status of its internal request The Promise exposes only theDeferred methods needed to at tach addit ional handlers or determine the state (then done failisResolved and isRejected) but not ones that change the state (resolve reject resolveWithand rejectWith) As of jQuery 16 the Promise also exposes the always and pipe Deferredmethods

If target is provided deferredpromise() will at tach the methods onto it and then return thisobject rather than create a new one This can be useful to at tach the Promise behavior to anobject that already exists

If you are creat ing a Deferred keep a reference to the Deferred so that it can be resolved orrejected at some point Return only the Promise object via deferredpromise() so other codecan register callbacks or inspect the current state

For more informat ion see the documentat ion for Deferred object

Example 1 Create a Deferred and set two t imer-based funct ions to either resolve or reject theDeferred af ter a random interval Whichever one f ires f irst wins and will call one of thecallbacks The second t imeout has no ef fect since the Deferred is already complete (in aresolved or rejected state) f rom the f irst t imeout act ion

Javascript

Create a Deferred and return its Promisefunction asyncEvent() var dfd = new jQueryDeferred() setTimeout(function() dfdresolve(hurray) Mathfloor(Mathrandom()1500)) setTimeout(function() dfdreject(sorry) Mathfloor(Mathrandom()1500)) return dfdpromise()

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

Example 2 Use the target argument to promote an exist ing object to a Promise

Javascript

Existing objectvar obj = hello function( name ) alert( Hello + name ) Create a Deferreddefer = $Deferred()

Set object as a promisedeferpromise( obj )

Resolve the deferreddeferresolve( John )

Use the object as a Promiseobjdone(function( name ) objhello( name ) wil l alert Hello John)hello( Karl ) wil l alert Hello Karl

jQuerywhen see Core

deferredresolveWith

Resolve a Deferred object and call any doneCallbacks with the given context and args

Added in version 15

deferredresolveWith(context args)Deferred

context Object Context passed to the doneCallbacks as the this object

argsArray (opt ional) An opt ional array of arguments that are passed to thedoneCallbacks

Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

deferredrejectWith

Reject a Deferred object and call any failCallbacks with the given context and args

Added in version 15

deferredrejectWith(context args)Deferred

context Object Context passed to the failCallbacks as the this object

argsArray (opt ional) An opt ional array of arguments that are passed to thefailCallbacks

Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

deferredfail

Add handlers to be called when the Deferred object is rejected

Added in version 15

deferredfail(failCallbacks failCallbacks)Deferred

failCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is rejected

failCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is rejected

The deferredfail() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is rejected the failCallbacks are calledCallbacks are executed in the order they were added Since deferredfail() returns the deferredobject other methods of the deferred object can be chained to this one including addit ionaldeferredfail() methods The failCallbacks are executed using the arguments provided to thedeferredreject() or deferredrejectWith() method call in the order they were added For moreinformat ion see the documentat ion for Deferred object

Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred you can at tach a success and failure callback using the deferreddone() anddeferredfail() methods

Javascript

$get(testphp) done(function() alert($get succeeded) ) fai l(function() alert($get fai led) )

deferreddone

Add handlers to be called when the Deferred object is resolved

Added in version 15

deferreddone(doneCallbacks doneCallbacks)Deferred

doneCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is resolved

doneCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is resolved

The deferreddone() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is resolved the doneCallbacks are calledCallbacks are executed in the order they were added Since deferreddone() returns thedeferred object other methods of the deferred object can be chained to this one includingaddit ional done() methods When the Deferred is resolved doneCallbacks are executed usingthe arguments provided to the resolve or resolveWith method call in the order they were addedFor more informat ion see the documentat ion for Deferred object

Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach a success callback using the done() method

Javascript

$get(testphp)done(function() alert($get succeeded) )

Example 2 Resolve a Deferred object when the user clicks a button t riggering a number ofcallback funct ions

Javascript

3 functions to call when the Deferred object is resolvedfunction fn1() $(p)append( 1 )function fn2() $(p)append( 2 )function fn3(n) $(p)append(n + 3 + n)

create a deferred objectvar dfd = $Deferred()

add handlers to be called when dfd is resolveddfd done() can take any number of functions or arrays of functionsdone( [fn1 fn2] fn3 [fn2 fn1] ) we can chain done methods toodone(function(n) $(p)append(n + were done))

resolve the Deferred object when the button is cl icked$(button)bind(click function() dfdresolve(and))

HTML

ltbuttongtGoltbuttongt ltpgtReadyltpgt

deferredthen

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

Added in version 15

deferredthen(doneCallbacks failCallbacks)Deferred

doneCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isresolved

failCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isrejected

Both arguments can be either a single funct ion or an array of funct ions Either argument can

also be null if no callback of that type is desired Alternat ively use done() or fail() to set onlydoneCallbacks or failCallbacks When the Deferred is resolved the doneCallbacks are called Ifthe Deferred is instead rejected the failCallbacks are called Callbacks are executed in the orderthey were added Since deferredthen returns the deferred object other methods of thedeferred object can be chained to this one including addit ional then() methods For moreinformat ion see the documentat ion for Deferred object

Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach handlers using the then method

Javascript

$get(testphp)then( function() alert($get succeeded) function() alert($get fai led) )

deferredreject

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

Added in version 15

deferredreject(args)Deferred

argsObject Opt ional arguments that are passed to the failCallbacks

Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

deferredisRejected

Determine whether a Deferred object has been rejected

Added in version 15

deferredisRejected()Boolean

Returns t rue if the Deferred object is in the rejected state meaning that either deferredreject()

or deferredrejectWith() has been called for the object and the failCallbacks have been called (orare in the process of being called)

Note that a Deferred object can be in one of three states unresolved resolved or rejecteduse deferredisResolved() to determine whether the Deferred object is in the resolved stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

deferredisResolved

Determine whether a Deferred object has been resolved

Added in version 15

deferredisResolved()Boolean

Returns t rue if the Deferred object is in the resolved state meaning that eitherdeferredresolve() or deferredresolveWith() has been called for the object and thedoneCallbacks 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 rejecteduse deferredisRejected() to determine whether the Deferred object is in the rejected stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

deferredresolve

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

Added in version 15

deferredresolve(args)Deferred

argsObject Opt ional arguments that are passed to the doneCallbacks

When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

Effects

fadeToggle

Display or hide the matched elements by animat ing their opacity

Added in version 144

fadeToggle(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackFunct ion (opt ional) A funct ion to call once the animat ion is complete

The fadeToggle() method animates the opacity of the matched elements When called on avisible element the element s display style property is set to none once the opacity reaches 0so the element no longer af fects the layout of the page

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

Easing

The string represent ing an easing funct ion specif ies the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easing implementat ions in thejQuery library are the default called swing and one that progresses at a constant pace calledlinear More easing funct ions are available with the use of plug-ins most notably the jQuery UIsuite

Callback Function

If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

As of jQuery 16 the promise() method can be used in conjunct ion with the deferreddone()method to execute a single callback for the animat ion as a whole when all matching elementshave completed their animat ions ( See the example for promise() )

Example 1 Fades f irst paragraph in or out complet ing the animat ion within 600 millisecondsand using a linear easing Fades last paragraph in or out for 200 milliseconds insert ing af inished message upon complet ion

Javascript

$(buttonfirst)cl ick(function() $(pfirst)fadeToggle(slow l inear))$(buttonlast)cl ick(function () $(plast)fadeToggle(fast function () $(log)append(ltdivgtfinishedltdivgt) ))

HTML

ltbuttongtfadeToggle p1ltbuttongtltbuttongtfadeToggle p2ltbuttongtltpgtThis paragraph has a slow l inear fadeltpgt

ltpgtThis paragraph has a fast animationltpgtltdiv id=loggtltdivgt

jQueryfxinterval

The rate (in milliseconds) at which animat ions f ire

Added in version 143

This property can be manipulated to adjust the number of f rames per second at whichanimat ions will run The default is 13 milliseconds Making this a lower number could make theanimat ions run smoother in faster browsers (such as Chrome) but there may be performanceand CPU implicat ions of doing so

Since jQuery uses one global interval no animat ion should be running or all animat ions shouldstop for the change of this property to take ef fect

NotejQueryfxinterval current ly has no ef fect in browsers that support therequestAnimat ionFrame property such as Google Chrome 11 This behavior is subject tochange in a future release

Example 1 Cause all animat ions to run with less f rames

Javascript

jQueryfxinterval = 100

$(input)cl ick(function() $(div)toggle( 3000 ))

CSS

div width50px height30px margin5px floatleft backgroundgreen

HTML

ltpgtltinput type=button value=Rungtltpgtltdivgtltdivgt

delay

Set a t imer to delay execut ion of subsequent items in the queue

Added in version 14

delay(durat ion queueName)jQuery

durat ionInteger An integer indicat ing the number of milliseconds to delay execut ionof the next item in the queue

queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

Added to jQuery in version 14 the delay() method allows us to delay the execut ion offunct ions that follow it in the queue It can be used with the standard ef fects queue or with acustom queue Only subsequent events in a queue are delayed for example this will not delaythe no-arguments forms of show() or hide() which do not use the ef fects queue

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

Using the standard ef fects queue we can for example set an 800-millisecond delay betweenthe slideUp() and fadeIn() of ltdiv id=foogt

$(foo)sl ideUp(300)delay(800)fadeIn(400)

When this statement is executed the element slides up for 300 milliseconds and then pausesfor 800 milliseconds before fading in for 400 milliseconds

The delay() method is best for delaying between queued jQuery effects Because

it is limitedacirceurordquoit doesnt for example offer a way to cancel the delayacirceurordquodelay() isnot a replacement for JavaScripts native setTimeout function which may be moreappropriate for certain use cases

Example 1 Animate the hiding and showing of two divs delaying the f irst before showing it

CSS

div position absolute width 60px height 60px float left first background-color 3f3 left 0second background-color 33f left 80px

Javascript

$(button)cl ick(function() $(divfirst)sl ideUp(300)delay(800)fadeIn(400) $(divsecond)sl ideUp(300)fadeIn(400) )

HTML

ltpgtltbuttongtRunltbuttongtltpgtltdiv class=firstgtltdivgtltdiv class=secondgtltdivgt

jQueryfxoff

Globally disable all animat ions

Added in version 13

When this property is set to t rue all animat ion methods will immediately set elements to theirf inal state when called rather than displaying an ef fect This may be desirable for a couplereasons

jQuery is being used on a low-resource device

Users are encountering accessibility problems with the animat ions (see the art icle TurnOff Animat ion for more informat ion)

Animat ions can be turned back on by sett ing the property to false

Example 1 Toggle animat ion on and of f

Javascript

var toggleFx = function() $fxoff = $fxofftoggleFx()

$(button)cl ick(toggleFx)

$(input)cl ick(function() $(div)toggle(slow))

CSS

div width50px height30px margin5px floatleft backgroundgreen

HTML

ltpgtltinput type=button value=Rungt ltbuttongtToggle fxltbuttongtltpgtltdivgtltdivgt

clearQueue see Data

dequeue see Data

queue see Data

queue see Data

stop

Stop the current ly-running animat ion on the matched elements

Added in version 12

stop(clearQueue jumpToEnd)jQuery

clearQueueBoolean (opt ional) A Boolean indicat ing whether to remove queuedanimat ion as well Defaults to false

jumpToEndBoolean (opt ional) A Boolean indicat ing whether to complete the currentanimat ion immediately Defaults to false

When stop() is called on an element the current ly-running animat ion (if any) is immediatelystopped If for instance an element is being hidden with slideUp() when stop() is called theelement will now st ill be displayed but will be a f ract ion of its previous height Callback funct ions

are not called

If more than one animat ion method is called on the same element the later animat ions areplaced in the ef fects queue for the element These animat ions will not begin unt il the f irst onecompletes When stop() is called the next animat ion in the queue begins immediately If theclearQueue parameter is provided with a value of t rue then the rest of the animat ions in thequeue are removed and never run

If the jumpToEnd property is provided with a value of t rue the current animat ion stops but theelement is immediately given its target values for each CSS property In our above slideUp()example the element would be immediately hidden The callback funct ion is then immediatelycalled if provided

The usefulness of the stop() method is evident when we need to animate an element onmouseenter and mouseleave

ltdiv id=hovermegt Hover me ltimg id=hoverme src=bookpng alt= width=100 height=123 gtltdivgt

We can create a nice fade ef fect without the common problem of mult iple queued animat ionsby adding stop(true t rue) to the chain

$(hoverme-stop-2)hover(function() $(this)find( img)stop(true true)fadeOut() function() $(this)find( img)stop(true true)fadeIn())

Animations may be stopped globally by setting the property $fxoff to true Whenthis is done all animation methods will immediately set elements to their finalstate when called rather than displaying an effect

Example 1 Click the Go button once to start the animat ion then click the STOP button to stopit where it s current ly posit ioned Another opt ion is to click several buttons to queue them upand see that stop just kills the current ly playing one

Javascript

Start animation $(go)cl ick(function()$(block)animate(left +=100px 2000))

Stop animation when button is cl icked $(stop)cl ick(function()$(block)stop())

Start animation in the opposite direction $(back)cl ick(function()$(block)animate(left -=100px 2000))

HTML

ltbutton id=gogtGoltbuttongt ltbutton id=stopgtSTOPltbuttongtltbutton id=backgtBackltbuttongtltdiv class=blockgtltdivgt

CSS

div position absolute background-color abcleft 0pxtop30pxwidth 60px height 60pxmargin 5px

animate

Perform a custom animat ion of a set of CSS propert ies

Added in version 10

animate(propert ies opt ions)jQuery

propert iesMap A map of CSS propert ies that the animat ion will move toward

opt ionsMap A map of addit ional opt ions to pass to the method Supported keys

durat ion A string or number determining how long theanimat ion will run

easing A string indicat ing which easing funct ion to use for thetransit ion

complete A funct ion to call once the animat ion is completestep A funct ion to be called af ter each step of the animat ionqueue A Boolean indicat ing whether to place the animat ion in

the ef fects queue If false the animat ion will begin immediatelyspecialEasing A map of one or more of the CSS propert ies

def ined by the propert ies argument and their correspondingeasing funct ions (added 14)

The animate() method allows us to create animat ion ef fects on any numeric CSS property Theonly required parameter is a map of CSS propert ies This map is similar to the one that can besent to the css() method except that the range of propert ies is more restrict ive

Animation Properties and Values

All animated propert ies should be animated to a single numeric value except as noted belowmost propert ies that are non-numeric cannot be animated using basic jQuery funct ionality (Forexample width height or lef t can be animated but background-color cannot be) Propertyvalues are t reated as a number of pixels unless otherwise specif ied The units em and can bespecif ied where applicable

In addit ion to style propert ies some non-style propert ies such as scrollTop and scrollLef t aswell as custom propert ies can be animated

Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

In addit ion to numeric values each property can take the strings show hide and toggleThese shortcuts allow for custom hiding and showing animat ions that take into account thedisplay type of the element

Animated propert ies can also be relat ive If a value is supplied with a leading += or -= sequenceof characters then the target value is computed by adding or subtract ing the given numberfrom the current value of the property

Unlike shorthand animat ion methods such as slideDown() and fadeIn() the animate() methoddoes not make hidden elements visible as part of the ef fect For example given$(someElement )hide()animate(height20px 500) the animat ion will run but the element willremain hidden

Duration

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

Complete Function

If supplied the complete callback funct ion is f ired once the animat ion is complete This can beuseful for stringing dif ferent animat ions together in sequence The callback is not sent anyarguments but this is set to the DOM element being animated If mult iple elements areanimated the callback is executed once per matched element not once for the animat ion as awhole

Basic Usage

To animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 style=position relative left 10px gt

To animate the opacity lef t of fset and height of the image simultaneously

$(clickme)cl ick(function() $(book)animate( opacity 025 left +=50 height toggle 5000 function() Animation complete ))

Note that the target value of the height property is toggle Since the image was visible beforethe animat ion shrinks the height to 0 to hide it A second click then reverses this t ransit ion

The opacity of the image is already at its target value so this property is not animated by thesecond click Since the target value for lef t is a relat ive value the image moves even farther tothe right during this second animat ion

Direct ional propert ies (top right bot tom lef t ) have no discernible ef fect on elements if theirposit ion style property is stat ic which it is by default

Note The jQuery UI project extends the animate() method by allowing some non-numeric styles such as colors to be animated The project also includesmechanisms for specifying animations through CSS classes rather than individualattributes

Note if attempting to animate an element with a height or width of 0px wherecontents of the element are visible due to overflow jQuery may clip this overflowduring animation By fixing the dimensions of the original element being hiddenhowever it is possible to ensure that the animation runs smoothly A clearfix canbe used to automatically fix the dimensions of your main element without the needto set this manually

Step Function

The second version of animate() provides a step opt ion acirceurordquo a callback funct ion that is f ired ateach step of the animat ion This funct ion is useful for enabling custom animat ion types oraltering the animat ion as it is occurring It accepts two arguments (now and fx) and this is setto the DOM element being animated

now the numeric value of the property being animated at each step

fx a reference to the jQueryfx prototype object which contains a number of propert iessuch as elem for the animated element start and end for the f irst and last value of theanimated property respect ively and prop for the property being animated

Note that the step funct ion is called for each animated property on each animated element Forexample given two list items the step funct ion f ires four t imes at each step of the animat ion

$( l i )animate( opacity 5 height 50 step function(now fx) var data = fxelemid + + fxprop + + now $(body)append(ltdivgt + data + ltdivgt) )

Easing

The remaining parameter of animate() is a string naming an easing funct ion to use An easingfunct ion specif ies the speed at which the animat ion progresses at dif ferent points within theanimat ion The only easing implementat ions in the jQuery library are the default called swingand one that progresses at a constant pace called linear More easing funct ions are availablewith the use of plug-ins most notably the jQuery UI suite

Per-property Easing

As of jQuery version 14 you can set per-property easing funct ions within a single animate()call In the f irst version of animate() each property can take an array as its value The f irstmember of the array is the CSS property and the second member is an easing funct ion If a per-property easing funct ion is not def ined for a part icular property it uses the value of theanimate() methods opt ional easing argument If the easing argument is not def ined thedefault swing funct ion is used

For example to simultaneously animate the width and height with the swing easing funct ionand the opacity with the linear easing funct ion

$(clickme)cl ick(function() $(book)animate( width [toggle swing] height [toggle swing] opacity toggle 5000 l inear function() $(this)after(ltdivgtAnimation completeltdivgt) ))

In the second version of animate() the opt ions map can include the specialEasing propertywhich is itself a map of CSS propert ies and their corresponding easing funct ions For exampleto simultaneously animate the width using the linear easing funct ion and the height using the

easeOutBounce easing funct ion

$(clickme)cl ick(function() $(book)animate( width toggle height toggle duration 5000 specialEasing width l inear height easeOutBounce complete function() $(this)after(ltdivgtAnimation completeltdivgt) ))

As previously noted a plugin is required for the easeOutBounce funct ion

Example 1 Click the button to animate the div with a number of dif ferent propert ies

Javascript

Using multiple unit types within one animation

$(go)cl ick(function() $(block)animate( width 70 opacity 04 marginLeft 06in fontSize 3em borderWidth 10px 1500 ))

HTML

ltbutton id=gogtampraquo Runltbuttongt

ltdiv id=blockgtHelloltdivgt

CSS

div background-colorbcawidth100pxborder1px solid green

Example 2 Animates a divs lef t property with a relat ive value Click several t imes on thebuttons to see the relat ive animat ions queued up

Javascript

$(right)cl ick(function() $(block)animate(left +=50px slow))

$(left)cl ick(function() $(block)animate(left -=50px slow))

HTML

ltbutton id=leftgtamplaquoltbuttongt ltbutton id=rightgtampraquoltbuttongtltdiv class=blockgtltdivgt

CSS

div positionabsolute background-colorabc left50px width90px height90px margin5px

Example 3 The f irst but ton shows how an unqueued animat ion works It expands the div out to90 width while the font-size is increasing Once the font-size change is complete the borderanimat ion will begin The second button starts a t radit ional chained animat ion where eachanimat ion will start once the previous animat ion on the element has completed

Javascript

$( go1 )cl ick(function() $( block1 )animate( width 90 queue false duration 3000 ) animate( fontSize 24px 1500 ) animate( borderRightWidth 15px 1500 ))

$( go2 )cl ick(function() $( block2 )animate( width 90 1000 ) animate( fontSize 24px 1000 ) animate( borderLeftWidth 15px 1000 ))

$( go3 )cl ick(function() $( go1 )add( go2 )cl ick())

$( go4 )cl ick(function() $( div )css( width fontSize borderWidth ))

HTML

ltbutton id=go1gtampraquo Animate Block1ltbuttongtltbutton id=go2gtampraquo Animate Block2ltbuttongtltbutton id=go3gtampraquo Animate Bothltbuttongt

ltbutton id=go4gtampraquo Resetltbuttongtltdiv id=block1gtBlock1ltdivgtltdiv id=block2gtBlock2ltdivgt

CSS

div background-colorbca width200px height11em text-aligncenter border2px solid green margin3px font-size14pxbutton font-size14px

Example 4 Animates the f irst divs lef t property and synchronizes the remaining divs using thestep funct ion to set their lef t propert ies at each stage of the animat ion

Javascript

$( go )cl ick(function() $( blockfirst )animate( left 100 duration 1000 step function( now fx ) $( blockgt(0) )css( left now ) ))

CSS

div position relative background-color abc width 40px height 40px float left margin 5px

HTML

ltpgtltbutton id=gogtRun Acircraquoltbuttongtltpgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgt

Example 5 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

Javascript

$( p )animate( height toggle opacity toggle slow )

Example 6 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds

Javascript

$( p )animate( left 50 opacity 1 500 )

Example 7 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion Note this code will donothing unless the paragraph element is hidden

Javascript

$( p )animate( opacity show slow easein )

Example 8 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

Javascript

$( p )animate( height toggle opacity toggle duration slow )

Example 9 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds It also will do it outside the queue meaning itwill automat ically start without wait ing for its turn

Javascript

$( p )animate( left 50px opacity 1 duration 500 queue false )

Example 10 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion

Javascript

$( p )animate( opacity show duration slow easing easein )

Example 11 An example of using a callback funct ion The f irst argument is an array of CSSpropert ies the second specif ies that the animat ion should take 1000 milliseconds to completethe third states the easing type and the fourth argument is an anonymous callback funct ion

Javascript

$( p )animate( height200 width400 opacity 5 1000 l inear function() alert(all done) )

fadeTo

Adjust the opacity of the matched elements

Added in version 143

fadeTo(durat ion opacity easing callback)jQuery

durat ionStringNumber A string or number determining how long the animat ion will run

opacityNumber A number between 0 and 1 denot ing the target opacity

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The fadeTo() method animates the opacity of the matched elements

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied the default durat ion of 400 milliseconds is usedUnlike the other ef fect methods fadeTo() requires that durat ion be explicit ly specif ied

If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

We can animate any element such as a simple image

ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly shown we can dim it slowly $(clickme)cl ick(function() $(book)fadeTo(slow 05 function() Animation complete ) )

With durat ion set to 0 this method just changes the opacity CSSproperty so fadeTo(0 opacity) is the same as css(opacity opacity)

Example 1 Animates f irst paragraph to fade to an opacity of 033 (33about one third visible) complet ing the animat ion within 600milliseconds

Javascript

$(pfirst)cl ick(function () $(this)fadeTo(slow 033))

HTML

ltpgtClick this paragraph to see it fadeltpgt

ltpgtCompare to this one that wont fadeltpgt

Example 2 Fade div to a random opacity on each click complet ing theanimat ion within 200 milliseconds

Javascript

$(div)cl ick(function () $(this)fadeTo(fast Mathrandom()))

CSS

p width80px margin0 padding5px div width40px height40px positionabsolute divone top0 left0 backgroundf00 divtwo top20px left20px background0f0 divthree top40px left40px background00f

HTML

ltpgtAnd this is the l ibrary that John builtltpgt

ltdiv id=onegtltdivgtltdiv id=twogtltdivgtltdiv id=threegtltdivgt

Example 3 Find the right answer The fade will take 250 milliseconds andchange various styles when it completes

Javascript

var getPos = function (n) return (Mathfloor(n) 90) + px$(p)each(function (n) var r = Mathfloor(Mathrandom() 3)var tmp = $(this)text()$(this)text($(peq( + r + ))text())$(peq( + r + ))text(tmp)$(this)css(left getPos(n)))$(div)each(function (n) $(this)css(left getPos(n)) )css(cursor pointer)cl ick(function () $(this)fadeTo(250 025 function () $(this)css(cursor ) prev()css(font-weight bolder font-style ital ic) ) )

CSS

div p width80px height40px top0 margin0 positionabsolute padding-top8px p backgroundfcc text-aligncenter div backgroundblue

HTML

ltpgtWrongltpgtltdivgtltdivgtltpgtWrongltpgtltdivgtltdivgt

ltpgtRightltpgtltdivgtltdivgt

fadeOut

Hide the matched elements by fading them to t ransparent

Added in version 143

fadeOut(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The fadeOut() method animates the opacity of the matched elements Once the opacityreaches 0 the display style property is set to none so the element no longer af fects the layoutof the page

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

With the element init ially shown we can hide it slowly

$(clickme)cl ick(function() $(book)fadeOut(slow function() Animation complete ))

Note To avoid unnecessary DOM manipulation fadeOut() willnot hide an element that is already considered hidden Forinformation on which elements jQuery considers hidden seehidden Selector

Easing

As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

Callback Function

If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

Example 1 Animates all paragraphs to fade out complet ing theanimat ion within 600 milliseconds

Javascript

$(p)cl ick(function () $(p)fadeOut(slow) )

CSS

p font-size150 cursorpointer

HTML

ltpgt If you click on this paragraph youl l see it just fade away ltpgt

Example 2 Fades out spans in one sect ion that you click on

Javascript

$(span)cl ick(function () $(this)fadeOut(1000 function () $(div)text( + $(this)text() + has faded) $(this)remove() ) ) $(span)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

CSS

span cursorpointer spanhil ite backgroundyellow div displayinline colorred

HTML

lth3gtFind the modifiers - ltdivgtltdivgtlth3gt ltpgt If you ltspangtreallyltspangt want to go outside ltspangtin the coldltspangt then make sure to wear your ltspangtwarmltspangt jacket given to you by your ltspangtfavoriteltspangt teacher ltpgt

Example 3 Fades out two divs one with a linear easing and one with the default swingeasing

Javascript

$(btn1)cl ick(function() function complete() $(ltdivgt)text(thisid)appendTo(log) $(box1)fadeOut(1600 l inear complete) $(box2)fadeOut(1600 complete))

$(btn2)cl ick(function() $(div)show() $(log)empty())

CSS

boxbutton floatleft margin5px 10px 5px 0 box height80px width80px background090 log clearleft

HTML

ltbutton id=btn1gtfade outltbuttongtltbutton id=btn2gtshowltbuttongt

ltdiv id=loggtltdivgt

ltdiv id=box1 class=boxgtlinearltdivgtltdiv id=box2 class=boxgtswingltdivgt

fadeIn

Display the matched elements by fading them to opaque

Added in version 143

fadeIn(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The fadeIn() method animates the opacity of the matched elements

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

We can animate any element such as a simple image

ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly hidden we can show it slowly $(clickme)cl ick(function() $(book)fadeIn(slow function() Animation complete ) )

Easing

As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

Callback Function

If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

Example 1 Animates hidden divs to fade in one by one complet ing eachanimat ion within 600 milliseconds

Javascript

$(documentbody)cl ick(function () $(divhiddenfirst)fadeIn(slow) )

CSS

span colorred cursorpointer div margin3px width80px displaynone height80px floatleft divone backgroundf00 divtwo background0f0 divthree background00f

HTML

ltspangtClick hereltspangt

ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt

Example 2 Fades a red block in over the text Once the animat ion is done it quickly fades inmore text on top

Javascript

$(a)cl ick(function () $(div)fadeIn(3000 function () $(span)fadeIn(100) ) return false )

CSS

p positionrelative width400px height90px div positionabsolute width400px height65px font-size36px text-aligncenter coloryellow backgroundred padding-top25px top0 left0 displaynone span displaynone

HTML

ltpgt 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 (lta href=gtclickltagt) ltdivgtltspangtCENSOREDltspangtltdivgt

ltpgt

slideToggle

Display or hide the matched elements with a sliding mot ion

Added in version 143

slideToggle(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The slideToggle() method animates the height of the matched elements This causes lowerparts of the page to slide up or down appearing to reveal or conceal the items If the element isinit ially displayed it will be hidden if hidden it will be shown The display property is saved andrestored as needed If an element has a display value of inline then is hidden and shown it willonce again be displayed inline When the height reaches 0 af ter a hiding animat ion the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

Durat ions are given in milliseconds higher values indicate slower animat ions not faster ones

The strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

We will cause slideToggle() to be called when another element is clicked

$(clickme)cl ick(function() $(book)sl ideToggle(slow function() Animation complete ))

With the element init ially shown we can hide it slowly with the f irst click

A second click will show the element once again

Easing

As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

Callback Function

If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed their

animat ions ( See the example for promise() )

Example 1 Animates all paragraphs to slide up or down complet ing theanimat ion within 600 milliseconds

Javascript

$(button)cl ick(function () $(p)sl ideToggle(slow) )

CSS

p width400px

HTML

ltbuttongtToggleltbuttongt

ltpgt This is the paragraph to end all paragraphs You should feel ltemgtluckyltemgt to have seen such a paragraph in your l i fe Congratulations ltpgt

Example 2 Animates divs between dividers with a toggle that makessome appear and some disappear

Javascript

$(aa)cl ick(function () $(divnot(sti l l))sl ideToggle(slow function () var n = parseInt($(span)text() 10) $(span)text(n + 1) ) )

CSS

div backgroundb977d1 margin3px width60px height60px floatleft divsti l l background345 width5px divhider displaynone span colorred p clear left

HTML

ltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv style=displaynonegtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltpgtltbutton id=aagtToggleltbuttongt There have been ltspangt0ltspangt toggled divsltpgt

slideUp

Hide the matched elements with a sliding mot ion

Added in version 143

slideUp(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The slideUp() method animates the height of the matched elements This causes lower partsof the page to slide up appearing to conceal the items Once the height reaches 0 the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

With the element init ially shown we can hide it slowly

$(clickme)cl ick(function() $(book)sl ideUp(slow function() Animation complete ))

Easing

As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

Callback Function

If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

Example 1 Animates all divs to slide up complet ing the animat ion within400 milliseconds

Javascript

$(documentbody)cl ick(function () i f ($(divfirst)is(hidden)) $(div)show(slow) else $(div)sl ideUp() )

CSS

div background3d9a44 margin3px width80px height40px floatleft

HTML

Click me ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

ltdivgtltdivgt

Example 2 Animates the parent paragraph to slide up complet ing the animat ion within 200milliseconds Once the animat ion is done it displays an alert

Javascript

$(button)cl ick(function () $(this)parent()sl ideUp(slow function () $(msg)text($(button this)text() + has completed) ) )

CSS

div margin2px

HTML

ltdivgt ltbuttongtHide Oneltbuttongt ltinput type=text value=One gt

ltdivgtltdivgt ltbuttongtHide Twoltbuttongt ltinput type=text value=Two gt

ltdivgtltdivgt ltbuttongtHide Threeltbuttongt ltinput type=text value=Three gt

ltdivgtltdiv id=msggtltdivgt

slideDown

Display the matched elements with a sliding mot ion

Added in version 143

slideDown(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

The slideDown() method animates the height of the matched elements This causes lowerparts of the page to slide down making way for the revealed items

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

With the element init ially hidden we can show it slowly

$(clickme)cl ick(function() $(book)sl ideDown(slow function() Animation complete ))

Easing

As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

Callback Function

If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

Example 1 Animates all divs to slide down and show themselves over600 milliseconds

Javascript

$(documentbody)cl ick(function () if ($(divfirst)is(hidden)) $(div)sl ideDown(slow) else $(div)hide())

CSS

div backgroundde9a44 margin3px width80px height40px displaynone floatleft

HTML

Click meltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

Example 2 Animates all inputs to slide down complet ing the animat ion within 1000milliseconds Once the animat ion is done the input look is changed especially if it is the middleinput which gets the focus

Javascript

$(div)cl ick(function () $(this)css( borderStyleinset cursorwait )$(input)sl ideDown(1000function()$(this)css(border 2px red inset)fi lter(middle) css(background yellow) focus()$(div)css(visibil ity hidden)))

CSS

div backgroundcfd margin3px width50px text-aligncenter floatleft cursorpointerborder2px outset black font-weightbolder input displaynone width120px floatleft margin10px

HTML

ltdivgtPushltdivgtltinput type=text gtltinput type=text class=middle gt

ltinput type=text gt

toggle

Display or hide the matched elements

Added in version 13

toggle(showOrHide)jQuery

showOrHideBoolean A Boolean indicat ing whether to show or hide the elements

With no parameters the toggle() method simply toggles the visibility of elements

$(target)toggle()

The matched elements will be revealed or hidden immediately with no animat ion by changingthe CSS display property If the element is init ially displayed it will be hidden if hidden it will beshown The display property is saved and restored as needed If an element has a display valueof inline then is hidden and shown it will once again be displayed inline

When a durat ion is provided toggle() becomes an animat ion method The toggle() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 af ter a hiding animat ion the display style property is set to none to ensurethat the element no longer af fects the layout of the page

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

Note The event handling suite also has a method named toggle() Which one isfired depends on the set of arguments passed

As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use of

plug-ins most notably the jQuery UI suite

If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

We will cause toggle() to be called when another element is clicked

$(clickme)cl ick(function() $(book)toggle(slow function() Animation complete ))

With the element init ially shown we can hide it slowly with the f irst click

A second click will show the element once again

The second version of the method accepts a Boolean parameter If thisparameter is t rue then the matched elements are shown if false theelements are hidden In essence the statement

$(foo)toggle(showOrHide)

is equivalent to

i f ( showOrHide == true ) $(foo)show() else if ( showOrHide == false ) $(foo)hide()

Example 1 Toggles all paragraphs

Javascript

$(button)cl ick(function () $(p)toggle())

HTML

ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

Example 2 Animates all paragraphs to be shown if they are hidden andhidden if they are visible complet ing the animat ion within 600milliseconds

Javascript

$(button)cl ick(function () $(p)toggle(slow))

CSS

p backgrounddadfont-weightboldfont-size16px

HTML

ltbuttongtToggle emltbuttongt

ltpgtHiyaltpgtltpgtSuch interesting text ehltpgt

Example 3 Shows all paragraphs then hides them all back and forth

Javascript

var fl ip = 0$(button)cl ick(function () $(p)toggle( fl ip++ 2 == 0 ))

HTML

ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

hide

Hide the matched elements

Added in version 143

hide(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determininghow long the animat ion will run

easingString (opt ional) A string indicat ing whicheasing funct ion to use for the t ransit ion

callbackCallback (opt ional) A funct ion to call once theanimat ion is complete

With no parameters the hide() method is the simplest way to hide an element

$(target)hide()

The matched elements will be hidden immediately with no animat ion This is roughly equivalentto calling css(display none) except that the value of the display property is saved in jQuerysdata cache so that display can later be restored to its init ial value If an element has a displayvalue of inline then is hidden and shown it will once again be displayed inline

When a durat ion is provided hide() becomes an animat ion method The hide() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 the display style property is set to none to ensure that the element nolonger af fects the layout of the page

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly shown we can hide it slowly$(clickme)cl ick(function() $(book)hide(slow function() alert(Animation complete) ))

Example 1 Hides all paragraphs then the link on click

Javascript

$(p)hide() $(a)cl ick(function ( event ) eventpreventDefault() $(this)hide() )

HTML

ltpgtHelloltpgt lta href=gtClick to hide me tooltagt ltpgtHere is another paragraphltpgt

Example 2 Animates all shown paragraphs to hide slowly complet ingthe animat ion within 600 milliseconds

Javascript

$(button)cl ick(function () $(p)hide(slow) )

CSS

p backgrounddad font-weightbold

HTML

ltbuttongtHide emltbuttongt

ltpgtHiyaltpgt ltpgtSuch interesting text ehltpgt

Example 3 Animates all spans (words in this case) to hide fast ly complet ing each animat ionwithin 200 milliseconds Once each animat ion is done it starts the next one

Javascript

$(hidr)cl ick(function () $(spanlast-child)hide(fast function () use callee so dont have to name the function $(this)prev()hide(fast argumentscallee) ) ) $(showr)cl ick(function () $(span)show(2000) )

CSS

span backgrounddef3ca padding3px floatleft

HTML

ltbutton id=hidrgtHideltbuttongt ltbutton id=showrgtShowltbuttongt ltdivgt

ltspangtOnceltspangt ltspangtuponltspangt ltspangtaltspangt ltspangttimeltspangt ltspangtthereltspangt ltspangtwereltspangt ltspangtthreeltspangt ltspangtprogrammersltspangt

ltdivgt

Example 4 Hides the divs when clicked over 2 seconds then removes the div element when itshidden Try clicking on more than one box at a t ime

Javascript

for (var i = 0 i lt 5 i++) $(ltdivgt)appendTo(documentbody) $(div)cl ick(function () $(this)hide(2000 function () $(this)remove() ) )

CSS

div backgroundece023 width30px height40px margin2px floatleft

HTML

ltdivgtltdivgt

show

Display the matched elements

Added in version 143

show(durat ion easing callback)jQuery

durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

callbackCallback (opt ional) A funct ion to call once the animat ion is complete

With no parameters the show() method is the simplest way to display an element

$(target)show()

The matched elements will be revealed immediately with no animat ion This is roughlyequivalent to calling css(display block) except that the display property is restored towhatever it was init ially If an element has a display value of inline then is hidden and shown itwill once again be displayed inline

Note If using important in your styles such as display none important it is necessary tooverride the style using css(display block important ) should you wish for show() to funct ioncorrect ly

When a durat ion is provided show() becomes an animat ion method The show() methodanimates the width height and opacity of the matched elements simultaneously

Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

We can animate any element such as a simple image

ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly hidden we can show it slowly$(clickme)cl ick(function() $(book)show(slow function() Animation complete ))

Example 1 Animates all hidden paragraphs to show slowly complet ingthe animat ion within 600 milliseconds

Javascript

$(button)cl ick(function () $(p)show(slow) )

CSS

p backgroundyellow

HTML

ltbuttongtShow itltbuttongt

ltp style=display nonegtHello 2ltpgt

Example 2 Animates all hidden divs to show fast ly in order complet ingeach animat ion within 200 milliseconds Once each animat ion is done itstarts the next one

Javascript

$(showr)cl ick(function () $(diveq(0))show(fast function () use callee so dont have to name the function $(this)next(div)show(fast argumentscallee) ))$(hidr)cl ick(function () $(div)hide(2000))

CSS

div backgrounddef3ca margin3px width80px displaynone floatleft text-aligncenter

HTML

ltbutton id=showrgtShowltbuttongt ltbutton id=hidrgtHideltbuttongt ltdivgtHello 3ltdivgt

ltdivgthowltdivgt ltdivgtareltdivgt ltdivgtyoultdivgt

Example 3 Shows all span and input elements with an animat ion Once the animat ion is done itchanges the text

Javascript

function doIt() $(spandiv)show(slow) can pass in function name $(button)cl ick(doIt)

$(form)submit(function () if ($(input)val() == yes) $(p)show(4000 function () $(this)text(Ok DONE (now showing)) ) $(spandiv)hide(fast) to stop the submit return false )

CSS

span displaynone div displaynone p font-weightbold background-colorfcd

HTML

ltbuttongtDo itltbuttongt ltspangtAre you sure (type yes if you are) ltspangt ltdivgt ltformgt ltinput type=text value=asldkfjalsdfgt ltformgt ltdivgt ltp style=displaynonegtIm hiddenltpgt

Ajax

jQueryajaxPrefilter

Handle custom Ajax opt ions or modify exist ing opt ions before each request is sent and beforethey are processed by $ajax()

Added in version 15

jQueryajaxPref ilter(dataTypes handler(opt ions originalOpt ions jqXHR))undef ined

dataTypesString (opt ional) An opt ional string containing one or more

space-separated dataTypes

handler(opt ionsoriginalOpt ionsjqXHR)Funct ion

A handler to set default values for future Ajaxrequests

A typical pref ilter registrat ion using $ajaxPref ilter() looks like this

$ajaxPrefi lter( function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

where

opt ions are the request opt ions

originalOpt ions are the opt ions as provided to the ajax method unmodif ied and thuswithout defaults f rom ajaxSett ings

jqXHR is the jqXHR object of the request

Pref ilters are a perfect f it when custom opt ions need to be handled Given the following codefor example a call to $ajax() would automat ically abort a request to the same URL if thecustom abortOnRetry opt ion is set to t rue

var currentRequests =

$ajaxPrefi lter(function( options originalOptions jqXHR ) if ( optionsabortOnRetry ) i f ( currentRequests[ optionsurl ] ) currentRequests[ optionsurl ]abort() currentRequests[ optionsurl ] = jqXHR )

Pref ilters can also be used to modify exist ing opt ions For example the following proxies cross-domain requests through ht tpmydomainnetproxy

$ajaxPrefi lter( function( options ) if ( optionscrossDomain ) optionsurl = httpmydomainnetproxy + encodeURIComponent( optionsurl ) optionscrossDomain = false )

If the opt ional dataTypes argument is supplied the pref ilter will be only be applied to requestswith the indicated dataTypes For example the following only applies the given pref ilter toJSON and script requests

$ajaxPrefi lter( json script function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

The $ajaxPref ilter() method can also redirect a request to another dataType by returning thatdataType For example the following sets a request as script if the URL has some specif icpropert ies def ined in a custom isActuallyScript() funct ion

$ajaxPrefi lter(function( options ) if ( isActuallyScript( optionsurl ) ) return script )

This would ensure not only that the request is considered script but also that all the pref iltersspecif ically at tached to the script dataType would be applied to it

ajaxComplete

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

Added in version 10

ajaxComplete(handler(event XMLHttpRequest ajaxOpt ions))jQuery

handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

Whenever an Ajax request completes jQuery t riggers the ajaxComplete event Any and allhandlers that have been registered with the ajaxComplete() method are executed at this t ime

To observe this method in act ion we can set up a basic Ajax load request

ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

When the user clicks the button and the Ajax request completes the log message is displayed

Note Because ajaxComplete() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

All ajaxComplete handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxComplete handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

$(log)ajaxComplete(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxComplete handler The result is + xhrresponseHTML) )

Example 1 Show a message when an Ajax request completes

Javascript

$(msg)ajaxComplete(function(eventrequest settings) $(this)append(ltligtRequest Completeltl igt) )

serializeArray see Forms

serialize see Forms

jQueryajaxSetup

Set default values for future Ajax requests

Added in version 11

jQueryajaxSetup(opt ions)

opt ionsOpt ions A set of keyvalue pairs that conf igure the default Ajax request Allopt ions are opt ional

For details on the sett ings available for $ajaxSetup() see $ajax()

All subsequent Ajax calls using any funct ion will use the new sett ings unless overridden by theindividual calls unt il the next invocat ion of $ajaxSetup()

For example the following sets a default for the url parameter before pinging the serverrepeatedly

$ajaxSetup( url pingphp)

Now each t ime an Ajax request is made the pingphp URL will be used automat ically

$ajax( url not set here uses pingphp data name Dan)

Note Global callback functions should be set with their respective global Ajaxevent handler methodsacirceurordquoajaxStart() ajaxStop() ajaxComplete() ajaxError()ajaxSuccess() ajaxSend()acirceurordquorather than within the options object for$ajaxSetup()

Example 1 Sets the defaults for Ajax requests to the url xmlht tp disables global handlersand uses POST instead of GET The following Ajax requests then sends some data withouthaving to set anything else

Javascript

$ajaxSetup( url xmlhttp global false type POST

) $ajax( data myData )

ajaxSuccess

Attach a funct ion to be executed whenever an Ajax request completes successfully This is anAjax Event

Added in version 10

ajaxSuccess(handler(event XMLHttpRequest ajaxOpt ions))jQuery

handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

Whenever an Ajax request completes successfully jQuery t riggers the ajaxSuccess event Anyand all handlers that have been registered with the ajaxSuccess() method are executed at thist ime

To observe this method in act ion we can set up a basic Ajax load request

ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

When the user clicks the button and the Ajax request completes successfully the log messageis displayed

Note Because ajaxSuccess() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

All ajaxSuccess handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxSuccess handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

$(log)ajaxSuccess(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSuccess handler The ajax response was + xhrresponseHTML ) )

Example 1 Show a message when an Ajax request completes successfully

Javascript

$(msg)ajaxSuccess(function(evt request settings) $(this)append(ltligtSuccessful Requestltl igt) )

ajaxStop

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

Added in version 10

ajaxStop(handler())jQuery

handler()Funct ion The funct ion to be invoked

Whenever an Ajax request completes jQuery checks whether there are any other outstandingAjax requests If none remain jQuery t riggers the ajaxStop event Any and all handlers that havebeen registered with the ajaxStop() method are executed at this t ime The ajaxStop event isalso t riggered if the last outstanding Ajax request is cancelled by returning false within thebeforeSend callback funct ion

To observe this method in act ion we can set up a basic Ajax load request

ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

When the user clicks the button and the Ajax request completes the log message is displayed

Because ajaxStop() is implemented as a method of jQuery object instances we can use thethis keyword as we do here to refer to the selected elements within the callback funct ion

Example 1 Hide a loading message af ter all the Ajax requests have stopped

Javascript

$(loading)ajaxStop(function() $(this)hide() )

ajaxStart

Register a handler to be called when the f irst Ajax request begins This is an Ajax Event

Added in version 10

ajaxStart(handler())jQuery

handler()Funct ion The funct ion to be invoked

Whenever an Ajax request is about to be sent jQuery checks whether there are any otheroutstanding Ajax requests If none are in progress jQuery t riggers the ajaxStart event Any andall handlers that have been registered with the ajaxStart() method are executed at this t ime

To observe this method in act ion we can set up a basic Ajax load request

ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

When the user clicks the button and the Ajax request is sent the log message is displayed

Note Because ajaxStart() is implemented as a method of jQuery object instances we can usethe this keyword as we do here to refer to the selected elements within the callback funct ion

Example 1 Show a loading message whenever an Ajax request starts (and none is alreadyact ive)

Javascript

$(loading)ajaxStart(function() $(this)show() )

ajaxSend

Attach a funct ion to be executed before an Ajax request is sent This is an Ajax Event

Added in version 10

ajaxSend(handler(event jqXHR ajaxOpt ions))jQuery

handler(event jqXHR ajaxOpt ions)Funct ion The funct ion to be invoked

Whenever an Ajax request is about to be sent jQuery t riggers the ajaxSend event Any and allhandlers that have been registered with the ajaxSend() method are executed at this t ime

To observe this method in act ion we can set up a basic Ajax load request

ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

When the user clicks the button and the Ajax request is about to begin the log message isdisplayed

Note Because ajaxSend() is implemented as a method of jQuery instances we can use the thiskeyword as we do here to refer to the selected elements within the callback funct ion

All ajaxSend handlers are invoked regardless of what Ajax request is to be sent If we mustdif ferent iate between the requests we can use the parameters passed to the handler Eacht ime an ajaxSend handler is executed it is passed the event object the jqXHR object (in version14 XMLHttpRequestobject) and the sett ings object that was used in the creat ion of the Ajaxrequest For example we can restrict our callback to only handling events dealing with apart icular URL

$(log)ajaxSend(function(e jqxhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSend handler) )

Example 1 Show a message before an Ajax request is sent

Javascript

$(msg)ajaxSend(function(evt request settings) $(this)append(ltligtStarting request at + settingsurl + ltl igt) )

ajaxError

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

Added in version 10

ajaxError(handler(event jqXHR ajaxSett ings thrownError))jQuery

handler(event jqXHR ajaxSett ings thrownError)Funct ion The funct ion to be invoked

Whenever an Ajax request completes with an error jQuery t riggers the ajaxError event Any andall handlers that have been registered with the ajaxError() method are executed at this t ime

To observe this method in act ion set up a basic Ajax load request

ltbutton class=triggergtTriggerltbuttongtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

Attach the event handler to any element

$(divlog)ajaxError(function() $(this)text( Triggered ajaxError handler ))

Now make an Ajax request using any jQuery method

$(buttontrigger)cl ick(function() $(divresult)load( ajaxmissinghtml ))

When the user clicks the button and the Ajax request fails because the requested f ile ismissing the log message is displayed

Note Because ajaxError() is implemented as a method of jQuery object instances you can usethe this keyword within the callback funct ion to refer to the selected elements

All ajaxError handlers are invoked regardless of what Ajax request was completed Todif ferent iate between the requests you can use the parameters passed to the handler Eacht ime an ajaxError handler is executed it is passed the event object the jqXHR object (prior tojQuery 15 the XHR object) and the sett ings object that was used in the creat ion of the

request If the request failed because JavaScript raised an except ion the except ion object ispassed to the handler as a fourth parameter For example to restrict the error callback to onlyhandling events dealing with a part icular URL

$( divlog )ajaxError(function(e jqxhr settings exception) if ( settingsurl == ajaxmissinghtml ) $(this)text( Triggered ajaxError handler ) )

Example 1 Show a message when an Ajax request fails

Javascript

$(msg)ajaxError(function(event request settings) $(this)append(ltligtError requesting page + settingsurl + ltl igt))

jQuerypost

Load data f rom the server using a HTTP POST request

Added in version 10

jQuerypost(url data success(data textStatus jqXHR) dataType)jqXHR

urlString A string containing the URL to which the request is sent

dataMap String (opt ional) A map or string that is sent to the server with therequest

success(datatextStatusjqXHR)Funct ion

(opt ional) A callback funct ion that is executed if the requestsucceeds

dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

This is a shorthand Ajax funct ion which is equivalent to

$ajax( type POST url url data data success success dataType dataType)

The success callback funct ion is passed the returned data which will be an XML root elementor a text string depending on the MIME type of the response It is also passed the text statusof the response

As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object)

Most implementat ions will specify a success handler

$post(ajaxtesthtml function(data) $( result)html(data))

This example fetches the requested HTML snippet and inserts it on the page

Pages fetched with POST are never cached so the cache and ifModif ied opt ions injQueryajaxSetup() have no ef fect on these requests

The jqXHR Object

As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $post() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $post() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $post(examplephp 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 jqxhrcomplete(function() alert(second complete) )

Example 1 Request the test php page but ignore the return results

Javascript

$post(testphp)

Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

Javascript

$post(testphp name John time 2pm )

Example 3 pass arrays of data to the server (while st ill ignoring the return results)

Javascript

$post(testphp choices[] [ Jon Susan] )

Example 4 send form data using ajax requests

Javascript

$post(testphp $(testform)serial ize())

Example 5 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

Javascript

$post(testphp function(data) alert(Data Loaded + data) )

Example 6 Alert out the results f rom request ing test php with an addit ional payload of data(HTML or XML depending on what was returned)

Javascript

$post(testphp name John time 2pm function(data) alert(Data Loaded + data) )

Example 7 Gets the test php page content store it in a XMLHttpResponse object and appliesthe process() JavaScript funct ion

Javascript

$post(testphp name John time 2pm function(data) process(data) xml)

Example 8 Posts to the test php page and gets contents which has been returned in jsonformat (Johnt ime=gt2pm)) gt)

Javascript

$post(testphp func getNameAndTime function(data) consolelog(dataname) John consolelog(datatime) 2pm json)

Example 9 Post a form using ajax and put results in a div

Javascript

attach a submit handler to the form $(searchForm)submit(function(event)

stop form from submitting normally eventpreventDefault() get some values from elements on the page var $form = $( this ) term = $formfind( input[name=s] )val() url = $formattr( 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 )empty()append( content ) ) )

HTML

ltform action= id=searchFormgt ltinput type=text name=s placeholder=Search gt ltinput type=submit value=Search gt ltformgt lt-- the result of the search wil l be rendered inside this div --gt ltdiv id=resultgtltdivgt

jQuerygetScript

Load a JavaScript f ile f rom the server using a GET HTTP request then execute it

Added in version 10

jQuerygetScript(url success(data textStatus))jqXHR

urlString A string containing the URL to which the request is sent

success(datatextStatus)Funct ion

(opt ional) A callback funct ion that is executed if therequest succeeds

This is a shorthand Ajax funct ion which is equivalent to

$ajax( url url dataType script success success)

The callback is passed the returned JavaScript f ile This is generally not useful as the script willalready have run at this point

The script is executed in the global context so it can refer to other variables and use jQueryfunct ions Included scripts can have some impact on the current page

$(result)html(ltpgtLorem ipsum dolor sit ametltpgt)

Scripts are included and run by referencing the f ile name

$getScript(ajaxtestjs function(data textStatus) consolelog(data) data returned consolelog(textStatus) success consolelog(Load was performed))

Note Should you require an addit ional callback for errors when using the getScript() methodthe global ajaxError() callback event may be used to achieve this as follows

$( divlog )ajaxError(function(e jqxhr settings exception) if (settingsdataType==script) $(this)text( Triggered ajaxError handler ) )

Example 1 Load the of f icial jQuery Color Animat ion plugin dynamically and bind some coloranimat ions to occur once the new funct ionality is loaded

Javascript

$getScript(httpdevjquerycomviewtrunkpluginscolorjquerycolorjs function() $(go)cl ick(function() $(block)animate( backgroundColor pink 1000) delay(500) animate( backgroundColor blue 1000) ))

HTML

ltbutton id=gogtampraquo Runltbuttongt

ltdiv class=blockgtltdivgt

CSS

block background-color blue width 150px height 70px margin 10px

jQuerygetJSON

Load JSON-encoded data f rom the server using a GET HTTP request

Added in version 10

jQuerygetJSON(url data success(data textStatus jqXHR))jqXHR

urlString A string containing the URL to which the request issent

dataMap (opt ional) A map or string that is sent to the serverwith the request

success(data textStatusjqXHR)Funct ion

(opt ional) A callback funct ion that is executed if therequest succeeds

This is a shorthand Ajax funct ion which is equivalent to

$ajax( url url dataType json data data success callback)

Data that is sent to the server is appended to the URL as a query string If the value of the dataparameter is an object (map) it is converted to a string and url-encoded before it is appendedto the URL

Most implementat ions will specify a success handler

$getJSON(ajaxtestjson function(data) var items = []

$each(data function(key val) itemspush(ltli id= + key + gt + val + ltl igt) )

$(ltulgt class my-new-list html itemsjoin( ) )appendTo(body))

This example of course relies on the structure of the JSON f ile

one Singular sensation two Beady l ittle 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 success callback is passed the returned data which is typically a JavaScript object or arrayas def ined by the JSON structure and parsed using the $parseJSON() method It is also passedthe text status of the response

As of jQuery 15 the success callback funct ion receives a jqXHR object (in jQuery 14 itreceived the XMLHttpRequest object) However since JSONP and cross-domain GET requestsdo not use XHR in those cases the jqXHR and textStatus parameters passed to the successcallback are undef ined

Important As of jQuery 14 if the JSON file contains a syntax error the requestwill usually fail silently Avoid frequent hand-editing of JSON data for this reasonJSON is a data-interchange format with syntax rules that are stricter than those ofJavaScripts object literal notation For example all strings represented in JSONwhether they are properties or values must be enclosed in double-quotes Fordetails on the JSON format see httpjsonorg

JSONP

If the URL includes the string callback= (or similar as def ined by the server-side API) therequest is t reated as JSONP instead See the discussion of the jsonp data type in $ajax() for

more details

The jqXHR Object

As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $getJSON() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $getJSON()to chain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $getJSON(examplejson 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 abovejqxhrcomplete(function() alert(second complete) )

Example 1 Loads the four most recent cat pictures f rom the Flickr JSONP API

Javascript

$getJSON(httpapifl ickrcomservicesfeedsphotos_publicgnejsoncallback= tags cat tagmode any format json function(data) $each(dataitems function(iitem) $(ltimggt)attr(src itemmediam)appendTo(images) i f ( i == 3 ) return false ) )

HTML

ltdiv id=imagesgt

ltdivgt

CSS

img height 100px float left

Example 2 Load the JSON data f rom test js and access a name from the returned JSON data

Javascript

$getJSON(testjs function(json) alert(JSON Data + jsonusers[3]name) )

Example 3 Load the JSON data f rom test js passing along addit ional data and access a namefrom the returned JSON data

Javascript

$getJSON(testjs name John time 2pm function(json) alert(JSON Data + jsonusers[3]name) )

jQueryget

Load data f rom the server using a HTTP GET request

Added in version 10

jQueryget(url data success(data textStatus jqXHR) dataType)jqXHR

urlString A string containing the URL to which the request is sent

dataMap String (opt ional) A map or string that is sent to the server with therequest

success(datatextStatusjqXHR)Funct ion

(opt ional) A callback funct ion that is executed if the requestsucceeds

dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

This is a shorthand Ajax funct ion which is equivalent to

$ajax( url url data data success success dataType dataType)

The success callback funct ion is passed the returned data which will be an XML root elementtext string JavaScript f ile or JSON object depending on the MIME type of the response It isalso passed the text status of the response

As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object) However since JSONP and cross-domain GETrequests do not use XHR in those cases the (j)XHR and textStatus parameters passed to thesuccess callback are undef ined

Most implementat ions will specify a success handler

$get(ajaxtesthtml 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

As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $get() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $get() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $get(examplephp 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 jqxhrcomplete(function() alert(second complete) )

Example 1 Request the test php page but ignore the return results

Javascript

$get(testphp)

Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

Javascript

$get(testphp name John time 2pm )

Example 3 pass arrays of data to the server (while st ill ignoring the return results)

Javascript

$get(testphp choices[] [ Jon Susan] )

Example 4 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

Javascript

$get(testphp function(data)alert(Data Loaded + data))

Example 5 Alert out the results f rom request ing test cgi with an addit ional payload of data

(HTML or XML depending on what was returned)

Javascript

$get(testcgi name John time 2pm function(data) alert(Data Loaded + data) )

Example 6 Gets the test php page contents which has been returned in json format(Johnt ime=gt2pm)) gt) and adds it to the page

Javascript

$get(testphp function(data) $(body)append( Name + dataname ) John append( Time + datatime ) 2pm json)

load

Load data f rom the server and place the returned HTML into the matched element

Added in version 10

load(url data complete(responseText textStatus XMLHttpRequest))jQuery

urlString A string containing the URL to which therequest is sent

dataMap String A map or string that is sent to the server withthe request

complete(responseText textStatusXMLHttpRequest)Funct ion

(opt ional) A callback funct ion that is executedwhen the request completes

This method is the simplest way to fetch data f rom the server It is roughly equivalent to$get(url data success) except that it is a method rather than global funct ion and it has animplicit callback funct ion When a successful response is detected (ie when textStatus issuccess or notmodif ied) load() sets the HTML contents of the matched element to thereturned data This means that most uses of the method can be quite simple

$(result)load(ajaxtesthtml)

The provided callback if any is executed af ter this post-processing has been performed

$(result)load(ajaxtesthtml function() alert(Load was performed))

In the two examples above if the current document does not contain an element with an ID ofresult the load() method is not executed

The POST method is used if data is provided as an object otherwise GET is assumed

Note The event handling suite also has a method named load() Which one isfired depends on the set of arguments passed

Loading Page Fragments

The load() method unlike $get() allows us to specify a port ion of the remote document to beinserted This is achieved with a special syntax for the url parameter If one or more spacecharacters are included in the string the port ion of the string following the f irst space isassumed 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(ajaxtesthtml container)

When this method executes it retrieves the content of ajaxtest html but then jQuery parsesthe returned document to f ind the element with an ID of container This element along with itscontents is inserted into the element with an ID of result and the rest of the retrieveddocument is discarded

jQuery uses the browsers innerHTML property to parse the retrieved document and insert itinto the current document During this process browsers of ten f ilter elements f rom thedocument such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements retrieved byload() may not be exact ly the same as if the document were retrieved direct ly by the browser

Example 1 Load the main pages footer navigat ion into an ordered list

Javascript

$(new-nav)load( jq-footerNavigation l i)

CSS

body font-size 12px font-family Arial

HTML

ltbgtFooter navigationltbgtltol id=new-navgtltolgt

Example 2 Display a not ice if the Ajax request encounters an error

Javascript

$(success)load(not-herephp function(response status xhr) if (status == error) var msg = Sorry but there was an error $(error)html(msg + xhrstatus + + xhrstatusText) )

CSS

body font-size 12px font-family Arial

HTML

ltbgtSuccessful Response (should be blank)ltbgtltdiv id=successgtltdivgtltbgtError Responseltbgtltdiv id=errorgtltdivgt

Example 3 Load the feedshtml f ile into the div with the ID of feeds

Javascript

$(feeds)load(feedshtml)

Results

ltdiv id=feedsgtltbgt45ltbgt feeds foundltdivgt

Example 4 pass arrays of data to the server

Javascript

$(objectID)load(testphp choices[] [ Jon Susan] )

Example 5 Same as above but will POST the addit ional parameters to the server and acallback that is executed when the server is f inished responding

Javascript

$(feeds)load(feedsphp limit 25 function()alert(The last 25 entries in the feed have been loaded))

jQueryajax

Perform an asynchronous HTTP (Ajax) request

Added in version 10

jQueryajax(sett ings)jqXHR

sett ingsMap A set of keyvalue pairs that conf igure the Ajax request All set t ings areopt ional A default can be set for any opt ion with $ajaxSetup()

The $ajax() funct ion underlies all Ajax requests sent by jQuery It is of ten unnecessary todirect ly call this funct ion as several higher-level alternat ives like $get() and load() are availableand are easier to use If less common opt ions are required though $ajax() can be used moref lexibly

At its simplest the $ajax() funct ion can be called with no arguments

$ajax()

Note Default set t ings can be set globally by using the $ajaxSetup() funct ion

This example using no opt ions loads the contents of the current page but does nothing withthe result To use the result we can implement one of the callback funct ions

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by $ajax() as of jQuery 15 is a supersetof the browsers nat ive XMLHttpRequest object For example it contains responseText andresponseXML propert ies as well as a getResponseHeader() method When the transport

mechanism is something other than XMLHttpRequest (for example a script tag for a JSONPrequest) the jqXHR object simulates nat ive XHR funct ionality where possible

As of jQuery 151 the jqXHR object also contains the overrideMimeType() method (it wasavailable in jQuery 14x as well but was temporarily removed in jQuery 15) TheoverrideMimeType() method may be used in the beforeSend() callback funct ion for exampleto modify the response content-type header

$ajax( url httpfiddlejshellnetfaviconpng beforeSend function( xhr ) xhroverrideMimeType( textplain charset=x-user-defined ) success function( data ) i f (console ampamp consolelog) consolelog( Sample of data datasl ice(0100) ) )

The jqXHR objects returned by $ajax() as of jQuery 15 implement the Promise interface givingthem all the propert ies methods and behavior of a Promise (see Deferred object for moreinformat ion) For convenience and consistency with the callback names used by $ajax() jqXHRalso provides error() success() and complete() methods These methods take a funct ionargument that is called when the $ajax() request terminates and the funct ion receives thesame arguments as the correspondingly-named $ajax() callback This allows you to assignmult iple callbacks on a single request and even to assign callbacks af ter the request may havecompleted (If the request is already complete the callback is f ired immediately)

Deprecation Notice The jqXHRsuccess() jqXHRerror() and jqXHRcomplete()callbacks will be deprecated in jQuery 18 To prepare your code for their eventualremoval use jqXHRdone() jqXHRfail() and jqXHRalways() instead

Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $ajax( examplephp ) success(function() alert(success) ) error(function() alert(error) ) complete(function() alert(complete) )

perform other work here

Set another completion function for the request abovejqxhrcomplete(function() alert(second complete) )

For backward compat ibility with XMLHttpRequest a jqXHR object will expose the followingpropert ies and methods

readyState

status

statusText

responseXML andor responseText when the underlying request responded with xmlandor text respect ively

setRequestHeader(name value) which departs f rom the standard by replacing the oldvalue with the new one rather than concatenat ing the new value to the old one

getAllResponseHeaders()

getResponseHeader()

abort()

No onreadystatechange mechanism is provided however since success error complete andstatusCode cover all conceivable requirements

Callback Function Queues

The beforeSend error dataFilter success and complete opt ions all accept callback funct ionsthat are invoked at the appropriate t imes

As of jQuery 15 the error (fail) success (done) and complete (always as of jQuery 16)callback hooks are f irst-in f irst-out managed queues This means you can assign more thanone callback for each hook See Deferred object methods which are implemented internally forthese $ajax() callback hooks

The this reference within all callbacks is the object in the context opt ion passed to $ajax in thesett ings if context is not specif ied this is a reference to the Ajax sett ings themselves

Some types of Ajax requests such as JSONP and cross-domain GET requests do not useXHR in those cases the XMLHttpRequest and textStatus parameters passed to the callbackare undef ined

Here are the callback hooks provided by $ajax()

1 beforeSend callback is invoked it receives the jqXHR object and the sett ings map asparameters

2 error callbacks are invoked in the order they are registered if the request fails Theyreceive the jqXHR a string indicat ing the error type and an except ion object if applicableSome built -in errors will provide a string as the except ion object abort t imeout NoTransport

3 dataFilter callback is invoked immediately upon successful receipt of response data Itreceives the returned data and the value of dataType and must return the (possiblyaltered) data to pass on to success

4 success callbacks are then invoked in the order they are registered if the requestsucceeds They receive the returned data a string containing the success code and thejqXHR object

5 complete callbacks f ire in the order they are registered when the request f inisheswhether in failure or success They receive the jqXHR object as well as a string containingthe success or error code

For example to make use of the returned HTML we can implement a success handler

$ajax( url ajaxtesthtml success function(data) $( result)html(data) alert(Load was performed) )

Data Types

The $ajax() funct ion relies on the server to provide informat ion about the retrieved data If theserver reports the return data as XML the result can be traversed using normal XML methodsor jQuerys selectors If another type is detected such as HTML in the example above the datais t reated as text

Dif ferent data handling can be achieved by using the dataType opt ion Besides plain xml thedataType can be html json jsonp script or text

The text and xml types return the data with no processing The data is simply passed on to thesuccess handler either through the responseText or responseXML property of the jqXHRobject respect ively

Note We must ensure that the MIME type reported by the web server matches our choice ofdataType In part icular XML must be declared by the server as text xml or applicat ionxml forconsistent results

If html is specif ied any embedded JavaScript inside the retrieved data is executed before theHTML is returned as a string Similarly script will execute the JavaScript that is pulled back fromthe server then return nothing

The json type parses the fetched data f ile as a JavaScript object and returns the constructedobject as the result data To do so it uses jQueryparseJSON() when the browser supports it

otherwise it uses a Funct ion constructor Malformed JSON data will throw a parse error (seejsonorg for more informat ion) JSON data is convenient for communicat ing structured data in away that is concise and easy for JavaScript to parse If the fetched data f ile exists on a remoteserver specify the jsonp type instead

The jsonp type appends a query string parameter of callback= to the URL The server shouldprepend the JSON data with the callback name to form a valid JSONP response We canspecify a parameter name other than callback with the jsonp opt ion to $ajax()

Note JSONP is an extension of the JSON format requiring some server-side code to detectand handle the query string parameter More informat ion about it can be found in the originalpost detailing its use

When data is retrieved from remote servers (which is only possible using the script or jsonpdata types) the error callbacks and global events will never be f ired

Sending Data to the Server

By default Ajax requests are sent using the GET HTTP method If the POST method isrequired the method can be specif ied by sett ing a value for the type opt ion This opt ionaffects how the contents of the data opt ion are sent to the server POST data will always betransmit ted to the server using UTF-8 charset per the W3C XMLHTTPRequest standard

The data opt ion can contain either a query string of the form key1=value1ampkey2=value2 or amap of the form key1 value1 key2 value2 If the lat ter form is used the data is convertedinto a query string using jQueryparam() before it is sent This processing can be circumventedby sett ing processData to false The processing might be undesirable if you wish to send anXML object to the server in this case change the contentType opt ion f rom applicat ionx-www-form-urlencoded to a more appropriate MIME type

Advanced Options

The global opt ion prevents handlers registered using ajaxSend() ajaxError() and similarmethods from f iring when this request would t rigger them This can be useful to for examplesuppress a loading indicator that was implemented with ajaxSend() if the requests are f requentand brief With cross-domain script and JSONP requests the global opt ion is automat ically setto false See the descript ions of these methods below for more details See the descript ions ofthese methods below for more details

If the server performs HTTP authent icat ion before providing a response the user name andpassword pair can be sent via the username and password opt ions

Ajax requests are t ime-limited so errors can be caught and handled to provide a better userexperience Request t imeouts are usually either lef t at their default or set as a global defaultusing $ajaxSetup() rather than being overridden for specif ic requests with the t imeout opt ion

By default requests are always issued but the browser may serve results out of its cache Todisallow use of the cached results set cache to false To cause the request to report failure ifthe asset has not been modif ied since the last request set ifModif ied to t rue

The scriptCharset allows the character set to be explicit ly specif ied for requests that use altscriptgt tag (that is a type of script or jsonp) This is useful if the script and host page havedif fering character sets

The f irst let ter in Ajax stands for asynchronous meaning that the operat ion occurs in paralleland the order of complet ion is not guaranteed The async opt ion to $ajax() defaults to t rueindicat ing that code execut ion can cont inue af ter the request is made Sett ing this opt ion tofalse (and thus making the call no longer asynchronous) is strongly discouraged as it can causethe browser to become unresponsive

The $ajax() funct ion returns the XMLHttpRequest object that it creates Normally jQueryhandles the creat ion of this object internally but a custom funct ion for manufacturing one canbe specif ied using the xhr opt ion The returned object can generally be discarded but doesprovide a lower-level interface for observing and manipulat ing the request In part icular callingabort() on the object will halt the request before it completes

Extending Ajax

As of jQuery 15 jQuerys Ajax implementat ion includes pref ilters converters and transportsthat allow you to extend Ajax with a great deal of f lexibility For more informat ion about theseadvanced features see the Extending Ajax page

Example 1 Load and execute a JavaScript f ile

Javascript

$ajax( type GET url testjs dataType script )

Example 2 Save some data to the server and not ify the user once it s complete

Javascript

$ajax( type POST url somephp data name=Johnamplocation=Boston success function(msg) alert( Data Saved + msg ) )

Example 3 Retrieve the latest version of an HTML page

Javascript

$ajax( url testhtml cache false success function(html) $(results)append(html) )

Example 4 Loads data synchronously Blocks the browser while the requests is act ive It isbetter to block user interact ion by other means when synchronizat ion is necessary

Javascript

var html = $ajax( url somephp async false )responseText

Example 5 Sends an xml document as data to the server By sett ing the processData opt ion tofalse the automat ic conversion of data to strings is prevented

Javascript

var xmlDocument = [create xml document] $ajax( url pagephp processData false data xmlDocument success handleResponse )

Example 6 Sends an id as data to the server save some data to the server and not ify the useronce it s complete Note that this usage - returning the result of the call into a variable -

requires a synchronous (blocking) request (asyncfalse)

Javascript

var bodyContent = $ajax( url scriptphp global false type POST data id thisgetAttribute( id) dataType html asyncfalse success function(msg) alert(msg) )responseText

jQueryparam see Forms

Miscellaneous

each see Traversing

toArray

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

Added in version 14

toArray()Array

toArray() returns all of the elements in the jQuery set

alert($( l i )toArray())

All of the matched DOM nodes are returned by this call contained in a standard array

[ltli id=foogt ltli id=bargt]

Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

Javascript

function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)toArray()reverse() )

CSS

span colorred

HTML

Reversed - ltspangtltspangt

ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

index

Search for a given element f rom among the matched elements

Added in version 10

index(element)Number

elementElementjQuery

The DOM element or f irst element within the jQuery object tolook for

Return Values

If no argument is passed to the index() method the return value is an integer indicat ing theposit ion of the f irst element within the jQuery object relat ive to its sibling elements

If index() is called on a collect ion of elements and a DOM element or jQuery object is passed inindex() returns an integer indicat ing the posit ion of the passed element relat ive to the originalcollect ion

If a selector string is passed as an argument index() returns an integer indicat ing the posit ionof the original element relat ive to the elements matched by the selector If the element is notfound index() will return -1

Detail

The complementary operat ion to get() which accepts an index and returns a DOM nodeindex() can take a DOM node and returns an index Suppose we have a simple unordered list onthe page

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgt

If we retrieve one of the three list items (for example through a DOM funct ion or as thecontext to an event handler) index() can search for this list item within the set of matchedelements

var l istItem = documentgetElementById(bar)alert( Index + $( l i )index(l istItem))We get back the zero-based position of the l ist item

Index 1

Similarly if we retrieve a jQuery object consist ing of one of the three list items index() willsearch for that list item

var l istItem = $(bar)alert( Index + $( l i )index(l istItem))

We get back the zero-based posit ion of the list item

Index 1

Note that if the jQuery collect ion used as the index() methods argument contains more thanone element the f irst element within the matched set of elements will be used

var l istItems = $( l i gt(0))alert( Index + $( l i )index(l istItems))

We get back the zero-based posit ion of the f irst list item within the matched set

Index 1

If we use a string as the index() methods argument it is interpreted as a jQuery selector string

The f irst element among the object s matched elements which also matches this selector islocated

var l istItem = $(bar)alert( Index + l istItemindex( l i ))

We get back the zero-based posit ion of the list item

Index 1

If we omit the argument index() will return the posit ion of the f irst element within the set ofmatched elements in relat ion to its siblings

alert( Index + $(bar)index()

Again we get back the zero-based posit ion of the list item

Index 1

Example 1 On click returns the index (based zero) of that div in the page

Javascript

$(div)cl ick(function () this is the dom element cl icked var index = $(div)index(this) $(span)text(That was div index + index))

CSS

div backgroundyellow margin5px span colorred

HTML

ltspangtClick a divltspangtltdivgtFirst divltdivgtltdivgtSecond divltdivgtltdivgtThird divltdivgt

Example 2 Returns the index for the element with ID bar

CSS

div font-weight bold color 090

Javascript

var l istItem = $(bar) $(div)html( Index + $( l i )index(l istItem) )

HTML

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

Example 3 Returns the index for the f irst item in the jQuery collect ion

CSS

div font-weight bold color 090

Javascript

var l istItems = $( l i gt(0))$(div)html( Index + $( l i )index(l istItems) )

HTML

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

Example 4 Returns the index for the element with ID bar in relat ion to all

elements

CSS

div font-weight bold color 090

Javascript

$(div)html( Index + $(bar)index( l i ) )

HTML

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

Example 5 Returns the index for the element with ID bar in relat ion to its siblings

CSS

div font-weight bold color 090

Javascript

var barIndex = $(bar)index()$(div)html( Index + barIndex )

HTML

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

Example 6 Returns -1 as there is no element with ID foobar

CSS

div font-weight bold color 090

Javascript

var foobar = $(l i)index( $(foobar) )$(div)html( Index + foobar)

HTML

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

removeData see Data

data see Data

data see Data

get

Retrieve the DOM elements matched by the jQuery object

Added in version 10

get(index)Element Array

indexNumber (opt ional) A zero-based integer indicat ing which element to retrieve

The get() method grants us access to the DOM nodes underlying each jQuery object Supposewe had a simple unordered list on the page

ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligtltulgt

Without a parameter get() returns all of the elements

alert($( l i )get())

All of the matched DOM nodes are returned by this call contained in a standard array

[ltli id=foogt ltli id=bargt]

With an index specif ied get() will retrieve a single element

($( l i )get(0))

Since the index is zero-based the f irst list item is returned

ltli id=foogt

Each jQuery object also masquerades as an array so we can use the array dereferencingoperator to get at the list item instead

alert($( l i )[0])

However this syntax lacks some of the addit ional capabilit ies of get() such as specifying anegat ive index

alert($( l i )get(-1))

A negat ive index is counted from the end of the matched set so this example will return thelast item in the list

ltli id=bargt

Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

Javascript

function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)get()reverse() )

CSS

span colorred

HTML

Reversed - ltspangtltspangt

ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

Example 2 Gives the tag name of the element clicked on

Javascript

$( documentbody)cl ick(function (e) estopPropagation() var domEl = $(this)get(0) $(spanfirst)text(Clicked on - + domEltagName) )

CSS

span colorred div backgroundyellow

HTML

ltspangtampnbspltspangt ltpgtIn this paragraph is an ltspangtimportantltspangt sectionltpgt

ltdivgtltinput type=text gtltdivgt

size

Return the number of elements in the jQuery object

Added in version 10

size()Number

The size() method is funct ionally equivalent to the length property however the lengthproperty is preferred because it does not have the overhead of a funct ion call

Given a simple unordered list on the page

ltulgt ltligtfooltligt ltligtbarltligtltulgt

Both size() and length ident ify the number of items

alert( Size + $(l i)size() )alert( Size + $(l i)length )

This results in two alerts

Size 2

Size 2

Example 1 Count the divs Click to add more

Javascript

$(documentbody)cl ick(function() $(this)append( $(ltdivgt) ) var n = $(div)size() $(span)text(There are + n + divs Click to add more)) trigger the cl ick to startcl ick()

CSS

body cursorpointer min-height 100px div width50px height30px margin5px floatleft backgroundblue span colorred

HTML

ltspangtltspangt ltdivgtltdivgt

jQuerynoConflict see Core

jQueryparam see Forms

Dimensions

outerWidth see CSS

outerHeight see CSS

innerWidth see CSS

innerHeight see CSS

width see CSS

width see CSS

height see CSS

height see CSS

Offset

offsetParent see Traversing

scrollLeft see CSS

scrollLeft see CSS

scrollTop see CSS

scrollTop see CSS

position see CSS

offset see CSS

offset see CSS

Utilities

jQuerynow

Return a number represent ing the current t ime

Added in version 143

jQuerynow()Number

The $now() method is a shorthand for the number returned by the expression (newDate)getTime()

jQueryparseXML

Parses a string into an XML document

Added in version 15

jQueryparseXML(data)XMLDocument

dataString a well-formed XML string to be parsed

jQueryparseXML uses the nat ive parsing funct ion of the browser to create a valid XMLDocument This document can then be passed to jQuery to create a typical jQuery object thatcan be traversed and manipulated

Example 1 Create a jQuery object using an XML string and obtain the value of the t it le node

HTML

ltp id=someElementgtltpgtltp id=anotherElementgtltpgt

Javascript

var xml = ltrss version=20gtltchannelgtlttitlegtRSS Titlelttitlegtltchannelgtltrssgt xmlDoc = $parseXML( xml ) $xml = $( xmlDoc ) $title = $xmlfind( title )

append RSS Title to someElement $( someElement )append( $titletext() )

change the title to XML Title $titletext( XML Title )

append XML Title to anotherElement $( anotherElement )append( $titletext() )

jQuerytype

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

Added in version 143

jQuerytype(obj)String

objObject 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

If the object is undef ined or null then undef ined or null is returned accordingly

If the object has an internal [[Class]] equivalent to one of the browsers built -in objectsthe associated name is returned (More details about this technique)

jQuerytype(true) === boolean

jQuerytype(3) === number

jQuerytype(test) === string

jQuerytype(funct ion()) === funct ion

jQuerytype([]) === array

jQuerytype(new Date()) === date

jQuerytype(test ) === regexp

Everything else returns object as its type

Example 1 Find out if the parameter is a RegExp

Javascript

$(b)append( + jQuerytype(test) )

HTML

Is it a RegExp ltbgtltbgt

jQueryisWindow

Determine whether the argument is a window

Added in version 143

jQueryisWindow(obj)boolean

objObject Object to test whether or not it is a window

This is used in a number of places in jQuery to determine if were operat ing against a browserwindow (such as the current window or an if rame)

Example 1 Finds out if the parameter is a window

Javascript

$(b)append( + $isWindow(window) )

HTML

Is window a window ltbgtltbgt

jQueryparseJSON

Takes a well-formed JSON string and returns the result ing JavaScript object

Added in version 141

jQueryparseJSON(json)Object

jsonString The JSON string to parse

Passing in a malformed JSON string may result in an except ion being thrown For example thefollowing are all malformed JSON strings

test 1 (test does not have double quotes around it )

test 1 (test is using single quotes instead of double quotes)

Addit ionally if you pass in nothing an empty string null or undef ined null will be returned fromparseJSON Where the browser provides a nat ive implementat ion of JSONparse jQuery uses itto parse the string For details on the JSON format see ht tpjsonorg

Example 1 Parse a JSON string

Javascript

var obj = jQueryparseJSON(nameJohn)alert( objname === John )

jQueryproxy see Events

jQuerycontains

Check to see if a DOM element is within another DOM element

Added in version 14

jQuerycontains(container contained)Boolean

containerElement The DOM element that may contain the other element

containedElement The DOM element that may be contained by the other element

Example 1 Check if an element is inside another Text and comment nodes are not supported

Javascript

jQuerycontains(documentdocumentElement documentbody) truejQuerycontains(documentbody documentdocumentElement) false

jQuerynoop

An empty funct ion

Added in version 14

jQuerynoop()Funct ion

You can use this empty funct ion when you wish to pass around a funct ion that will do nothing

This is useful for plugin authors who of fer opt ional callbacks in the case that no callback isgiven something like jQuerynoop could execute

jQueryglobalEval

Execute some JavaScript code globally

Added in version 104

jQueryglobalEval(code)

codeString The JavaScript code to execute

This method behaves dif ferent ly f rom using a normal JavaScript eval() in that it s executedwithin the global context (which is important for loading external scripts dynamically)

Example 1 Execute a script in the global context

Javascript

function test() jQueryglobalEval(var newVar = true)test() newVar === true

jQueryisXMLDoc

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

Added in version 114

jQueryisXMLDoc(node)Boolean

nodeElement The DOM node that will be checked to see if it s in an XML document

Example 1 Check an object to see if it s in an XML document

Javascript

jQueryisXMLDoc(document) falsejQueryisXMLDoc(documentbody) false

jQueryremoveData see Data

jQuerydata see Data

jQuerydata see Data

jQuerydequeue see Data

jQueryqueue see Data

jQueryqueue see Data

clearQueue see Data

jQueryisEmptyObject

Check to see if an object is empty (contains no propert ies)

Added in version 14

jQueryisEmptyObject(object)Boolean

object Object The object that will be checked to see if it s empty

As of jQuery 14 this method checks both propert ies on the object itself and propert iesinherited f rom prototypes (in that it doesnt use hasOwnProperty) The argument shouldalways be a plain JavaScript Object as other types of object (DOM elements primit ivestringsnumbers host objects) may not give consistent results across browsers To determine ifan object is a plain JavaScript object use $isPlainObject()

Example 1 Check an object to see if it s empty

Javascript

jQueryisEmptyObject() truejQueryisEmptyObject( foo bar ) false

jQueryisPlainObject

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

Added in version 14

jQueryisPlainObject(object)Boolean

object Object The object that will be checked to see if it s a plain object

Note Host objects (or objects used by browser host environments to complete the execut ionenvironment of ECMAScript) have a number of inconsistencies which are dif f icult to robust lyfeature detect cross-plat form As a result of this $isPlainObject() may evaluate inconsistent lyacross browsers in certain instances

An example of this is a test against documentlocat ion using $isPlainObject() as follows

consolelog($isPlainObject(documentlocation))

which throws an invalid pointer except ion in IE8 With this in mind it s important to be aware ofany of the gotchas involved in using $isPlainObject() against older browsers Some basicexample of use-cases that do funct ion correct ly cross-browser can be found below

Example 1 Check an object to see if it s a plain object

Javascript

jQueryisPlainObject() truejQueryisPlainObject(test) false

dequeue see Data

queue see Data

queue see Data

jQuerybrowser

Contains f lags for the useragent read from navigatoruserAgent We recommend against usingthis property please try to use feature detect ion instead (see jQuerysupport) jQuerybrowsermay be moved to a plugin in a future release of jQuery

Added in version 10

The $browser property provides informat ion about the web browser that is accessing thepage as reported by the browser itself It contains f lags for each of the four most prevalentbrowser classes (Internet Explorer Mozilla Webkit and Opera) as well as version informat ion

Available f lags are

webkit (as of jQuery 14)

safari (deprecated)

opera

msie

mozilla

This property is available immediately It is therefore safe to use it to determine whether or notto call $(document)ready() The $browser property is deprecated in jQuery 13 and itsfunct ionality may be moved to a team-supported plugin in a future release of jQuery

Because $browser uses navigatoruserAgent to determine the plat form it is vulnerable tospoof ing by the user or misrepresentat ion by the browser itself It is always best to avoidbrowser-specif ic code ent irely where possible The $support property is available for detect ionof support for part icular features rather than relying on $browser

Example 1 Show the browser info

Javascript

jQueryeach(jQuerybrowser function(i val) $(ltdivgt + i + ltspangt + val + ltspangt) appendTo( documentbody ) )

CSS

p colorgreen font-weightbolder margin3px 0 0 10px div colorblue margin-left20px font-size14px span colorred

HTML

ltpgtBrowser infoltpgt

Example 2 Returns t rue if the current useragent is some version of Microsoft s InternetExplorer

Javascript

$browsermsie

Example 3 Alerts this is WebKit only for WebKit browsers

Javascript

i f ($browserwebkit) alert( this is webkit )

Example 4 Alerts Do stuf f for Firefox 3 only for Firefox 3 browsers

Javascript

var ua = $browser i f ( uamozil la ampamp uaversionsl ice(03) == 19 ) alert( Do stuff for firefox 3 )

Example 5 Set a CSS property that s specif ic to a part icular browser

Javascript

i f ( $browsermsie ) $(div ul l i)css( display inl ine ) else $(div ul l i)css( display inl ine-table )

jQuerybrowserversion

The version number of the rendering engine for the users browser

Added in version 113

Here are some typical results

Internet Explorer 60 70 80

MozillaFirefoxFlockCamino 1712 1813 19

Opera 1006 1101

SafariWebkit 3128 4189

Note that IE8 claims to be 7 in Compat ibility View

Example 1 Returns the version number of the rendering engine used by the users currentbrowser For example FireFox 4 returns 20 (the version of the Gecko rendering engine itut ilizes)

Javascript

$(p)html( The version number of the rendering engine your browser uses is ltspangt + $browserversion + ltspangt )

CSS

p colorblue margin20px span colorred

HTML

ltpgtltpgt

Example 2 Alerts the version of IEs rendering engine that is being used

Javascript

i f ( $browsermsie ) alert( $browserversion )

Example 3 Often you only care about the major number the whole number which you canget by using JavaScript s built -in parseInt() funct ion

Javascript

i f ( $browsermsie ) alert( parseInt($browserversion 10) )

jQuerytrim

Remove the whitespace from the beginning and end of a string

Added in version 10

jQueryt rim(str)String

strString The string to t rim

The $t rim() funct ion removes all newlines spaces (including non-breaking spaces) and tabsfrom the beginning and end of the supplied string If these whitespace characters occur in themiddle of the string they are preserved

Example 1 Remove the two white spaces at the start and at the end of the string

Javascript

$(button)cl ick(function () var str = lots of spaces before and after alert( + str + )

str = jQuerytrim(str)alert( + str + - no longer))

HTML

ltbuttongtShow Trim Exampleltbuttongt

Example 2 Remove the two white spaces at the start and at the end of the string

Javascript

$trim( hello how are you )

Results

hello how are you

jQueryisFunction

Determine if the argument passed is a Javascript funct ion object

Added in version 12

jQueryisFunct ion(obj)boolean

objObject Object to test whether or not it is a funct ion

Note As of jQuery 13 funct ions provided by the browser like alert() and DOM elementmethods like getAttribute() are not guaranteed to be detected as funct ions in browsers suchas Internet Explorer

Example 1 Test a few parameter examples

Javascript

function stub() var objs = [ function () x15 y20 null stub function ]

jQueryeach(objs function (i) var isFunc = jQueryisFunction(objs[i]) $(span)eq(i)text(isFunc) )

CSS

div colorblue margin2px font-size14px span colorred

HTML

ltdivgtjQueryisFunction(objs[0]) = ltspangtltspangtltdivgt

ltdivgtjQueryisFunction(objs[1]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[2]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[3]) = ltspangtltspangtltdivgt

ltdivgtjQueryisFunction(objs[4]) = ltspangtltspangtltdivgt

Example 2 Finds out if the parameter is a funct ion

Javascript

$isFunction(function())

Results

true

jQueryisArray

Determine whether the argument is an array

Added in version 13

jQueryisArray(obj)boolean

objObject Object to test whether or not it is an array

$isArray() returns a Boolean indicat ing whether the object is a JavaScript array (not an array-like object such as a jQuery object)

Example 1 Finds out if the parameter is an array

Javascript

$(b)append( + $isArray([]) )

HTML

Is [] an Array ltbgtltbgt

jQueryunique

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

Added in version 113

jQueryunique(array)Array

arrayArray The Array of DOM elements

The $unique() funct ion searches through an array of objects sort ing the array and removingany duplicate nodes This funct ion only works on plain JavaScript arrays of DOM elements andis chief ly used internally by jQuery

As of jQuery 14 the results will always be returned in document order

Example 1 Removes any duplicate elements f rom the array of divs

Javascript

var divs = $(div)get() unique() must take a native array

add 3 elements of class dup too (they are divs) divs = divsconcat($(dup)get()) $(diveq(1))text(Pre-unique there are + divslength + elements)

divs = jQueryunique(divs) $(diveq(2))text(Post-unique there are + divslength + elements) css(color red)

CSS

div colorblue

HTML

ltdivgtThere are 6 divs in this documentltdivgt ltdivgtltdivgt ltdiv class=dupgtltdivgt ltdiv class=dupgtltdivgt

ltdiv class=dupgtltdivgt ltdivgtltdivgt

jQuerymerge

Merge the contents of two arrays together into the f irst array

Added in version 10

jQuerymerge(f irst second)Array

f irst Array The f irst array to merge the elements of second added

secondArray The second array to merge into the f irst unaltered

The $merge() operat ion forms an array that contains all elements f rom the two arrays Theorders of items in the arrays are preserved with items from the second array appended The$merge() funct ion is destruct ive It alters the f irst parameter to add the items from the second

If you need the original f irst array make a copy of it before calling $merge() Fortunately$merge() itself can be used for this duplicat ion

var newArray = $merge([] oldArray)

This shortcut creates a new empty array and merges the contents of oldArray into it ef fect ively cloning the array

Prior to jQuery 14 the arguments should be true Javascript Array objects use $makeArray ifthey are not

Example 1 Merges two arrays altering the f irst argument

Javascript

$merge( [012] [234] )

Results

[012234]

Example 2 Merges two arrays altering the f irst argument

Javascript

$merge( [321] [432] )

Results

[321432]

Example 3 Merges two arrays but uses a copy so the original isnt altered

Javascript

var first = [abc]var second = [de f]$merge( $merge([]first) second)

Results

[abcdef]

jQueryinArray

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

Added in version 12

jQueryinArray(value array)Number

valueAny The value to search for

arrayArray An array through which to search

The $inArray() method is similar to JavaScript s nat ive indexOf() method in that it returns -1when it doesnt f ind a match If the f irst element within the array matches value $inArray()returns 0

Because JavaScript t reats 0 as loosely equal to false (ie 0 == false but 0 == false) if werechecking for the presence of value within array we need to check if it s not equal to (or greaterthan) -1

Example 1 Report the index of some elements in the array

Javascript

var arr = [ 4 Pete 8 John ]

$(spaneq(0))text(jQueryinArray(John arr))$(spaneq(1))text(jQueryinArray(4 arr))$(spaneq(2))text(jQueryinArray(Karl arr))

CSS

div colorblue span colorred

HTML

ltdivgtJohn found at ltspangtltspangtltdivgtltdivgt4 found at ltspangtltspangtltdivgtltdivgtKarl not found so ltspangtltspangtltdivgt

jQuerymap

Translate all items in an array or object to new array of items

Added in version 16

jQuerymap(arrayOrObject callback( value indexOrKey ))Array

arrayOrObject ArrayObject The Array or Object to t ranslate

callback( value indexOrKey)Funct ion

The funct ion to process each item against The f irstargument to the funct ion is the value the secondargument is the index or key of the array or objectproperty The funct ion can return any value to add to thearray A returned array will be f lat tened into the result ingarray Within the funct ion this refers to the global (window)object

The $map() method applies a funct ion to each item in an array or object and maps the resultsinto a new array Prior to jQuery 16 $map() supports t raversing arrays only As of jQuery 16 italso t raverses objects

Array-like objects acirceurordquo those with a length property and a value on the length - 1 index acirceurordquo mustbe converted to actual arrays before being passed to $map() The jQuery library provides$makeArray() for such conversions

The following object masquerades as an arrayvar fakeArray = length 1 0 Addy 1 Subtracty

Therefore convert it to a real arrayvar realArray = $makeArray( fakeArray )

Now it can be used reliably with $map()$map( realArray function(val i) do something )

The translat ion funct ion that is provided to this method is called for each top-level element inthe array or object and is passed two arguments The element s value and its index or keywithin the array or object

The funct ion can return

the translated value which will be mapped to the result ing array

null to remove the item

an array of values which will be f lat tened into the full array

Example 1 A couple examples of using map()

Javascript

var arr = [ a b c d e ] $(div)text(arrjoin( ))

arr = jQuerymap(arr function(n i) return (ntoUpperCase() + i) ) $(p)text(arrjoin( ))

arr = jQuerymap(arr function (a) return a + a ) $(span)text(arrjoin( ))

CSS

div colorblue p colorgreen margin0 span colorred

HTML

ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

Example 2 Map the original array to a new one and add 4 to each value

Javascript

$map( [012] function(n) return n + 4 )

Results

[4 5 6]

Example 3 Maps the original array to a new one and adds 1 to each value if it is bigger thenzero otherwise it s removed

Javascript

$map( [012] function(n) return n gt 0 n + 1 null )

Results

[2 3]

Example 4 Map the original array to a new one each element is added with its original valueand the value plus one

Javascript

$map( [012] function(n) return [ n n + 1 ] )

Results

[0 1 1 2 2 3]

Example 5 Map the original object to a new array and double each value

Javascript

var dimensions = width 10 height 15 length 20 dimensions = $map( dimensions function( value index ) return value 2)

Results

[20 30 40]

Example 6 Map an object s keys to an array

Javascript

var dimensions = width 10 height 15 length 20 keys = $map( dimensions function( value index ) return index )

Results

[width height length]

Example 7 Maps the original array to a new one each element is squared

Javascript

$map( [0123] function (a) return a a )

Results

[0 1 4 9]

Example 8 Remove items by returning null f rom the funct ion This removes any numbers lessthan 50 and the rest are decreased by 45

Javascript

$map( [0 1 52 97] function (a) return (a gt 50 a - 45 null) )

Results

[7 52]

Example 9 Augment ing the result ing array by returning an array inside the funct ion

Javascript

var array = [0 1 52 97]array = $map(array function(a index) return [a - 45 index])

Results

[-45 0 -44 1 7 2 52 3]

jQuerymakeArray

Convert an array-like object into a t rue JavaScript array

Added in version 12

jQuerymakeArray(obj)Array

objObject Any object to turn into a nat ive Array

Many methods both in jQuery and in JavaScript in general return objects that are array-like Forexample the jQuery factory funct ion $() returns a jQuery object that has many of thepropert ies of an array (a length the [] array access operator etc) but is not exact ly the sameas an array and lacks some of an arrays built -in methods (such as pop() and reverse())

Note that af ter the conversion any special features the object had (such as the jQuerymethods in our example) will no longer be present The object is now a plain array

Example 1 Turn a collect ion of HTMLElements into an Array of them

Javascript

var elems = documentgetElementsByTagName(div) returns a nodeList var arr = jQuerymakeArray(elems) arrreverse() use an Array method on l ist of dom elements $(arr)appendTo(documentbody)

CSS

div colorred

HTML

ltdivgtFirstltdivgt ltdivgtSecondltdivgt ltdivgtThirdltdivgt

ltdivgtFourthltdivgt

Example 2 Turn a jQuery object into an array

Javascript

var obj = $( l i ) var arr = $makeArray(obj)

Results

(typeof obj === object ampamp objjquery) === truejQueryisArray(arr) === true

jQuerygrep

Finds the elements of an array which sat isfy a f ilter funct ion The original array is not af fected

Added in version 10

jQuerygrep(array funct ion(elementOfArray indexInArray) invert)Array

arrayArray The array to search through

funct ion(elementOfArrayindexInArray)Funct ion

The funct ion to process each item against The f irstargument to the funct ion is the item and the secondargument is the index The funct ion should return a Booleanvalue this will be the global window object

invert Boolean (opt ional) If invert is false or not provided then thefunct ion returns an array consist ing of all elements for whichcallback returns t rue If invert is t rue then the funct ionreturns an array consist ing of all elements for whichcallback returns false

The $grep() method removes items from an array as necessary so that all remaining items passa provided test The test is a funct ion that is passed an array item and the index of the itemwithin the array Only if the test returns t rue will the item be in the result array

The f ilter funct ion will be passed two arguments the current array item and its index The f ilterfunct ion must return t rue to include the item in the result array

Example 1 Filters the original array of numbers leaving that are not 5 and have an index greaterthan 4 Then it removes all 9s

Javascript

var arr = [ 1 9 3 8 6 1 5 9 4 7 3 8 6 9 1 ]$(div)text(arrjoin( ))

arr = jQuerygrep(arr function(n i) return (n = 5 ampamp i gt 4))$(p)text(arrjoin( ))

arr = jQuerygrep(arr function (a) return a = 9 )$(span)text(arrjoin( ))

CSS

div colorblue p colorgreen margin0 span colorred

HTML

ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

Example 2 Filter an array of numbers to include only numbers bigger then zero

Javascript

$grep( [012] function(ni) return n gt 0 )

Results

[1 2]

Example 3 Filter an array of numbers to include numbers that are not bigger than zero

Javascript

$grep( [012] function(ni) return n gt 0true)

Results

[0]

jQueryextend

Merge the contents of two or more objects together into the f irst object

Added in version 114

jQueryextend(deep target object1 objectN)Object

deepBoolean (opt ional) If t rue the merge becomes recursive (aka deep copy)

targetObject The object to extend It will receive the new propert ies

object1Object An object containing addit ional propert ies to merge in

objectNObject (opt ional) Addit ional objects containing propert ies to merge in

When we supply two or more objects to $extend() propert ies f rom all of the objects are addedto the target object

If only one argument is supplied to $extend() this means the target argument was omit ted Inthis case the jQuery object itself is assumed to be the target By doing this we can add newfunct ions to the jQuery namespace This can be useful for plugin authors wishing to add newmethods to JQuery

Keep in mind that the target object (f irst argument) will be modif ied and will also be returnedfrom $extend() If however we want to preserve both of the original objects we can do so bypassing an empty object as the target

var object = $extend( object1 object2)

The merge performed by $extend() is not recursive by default if a property of the f irst object isitself an object or array it will be completely overwrit ten by a property with the same key in thesecond object The values are not merged This can be seen in the example below by examiningthe value of banana However by passing true for the f irst funct ion argument objects will berecursively merged

Undef ined propert ies are not copied However propert ies inherited f rom the object s prototypewill be copied over For performance reasons propert ies that have values of built -in JavaScripttypes such as Date or RegExp are not re-constructed and will appear as plain Objects in theresult ing object or array

Note When performing a deep extend Object and Array are extended howeverprimitive types such string boolean and number are not For specific needs thatfall outside of this behaviour it is recommended to write a custom extend methodas this will be significantly faster from a performance perspective

Example 1 Merge two objects modifying the f irst

Javascript

var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

merge object2 into object1 $extend(object1 object2)

var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

$(log)append( printObj(object1) )

HTML

ltdiv id=loggtltdivgt

Example 2 Merge two objects recursively modifying the f irst

Javascript

var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

merge object2 into object1 recursively $extend(true object1 object2)

var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

$(log)append( printObj(object1) )

HTML

ltdiv id=loggtltdivgt

Example 3 Merge defaults and opt ions without modifying the defaults This is a commonplugin development pattern

Javascript

var defaults = validate false l imit 5 name foo var options = validate true name bar

merge defaults and options without modifying defaults var settings = $extend( defaults options)

var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

$(log)append( ltdivgtltbgtsettings -- ltbgt + printObj(settings) + ltdivgt )$(log)append( ltdivgtltbgtoptions -- ltbgt + printObj(options) + ltdivgt )

HTML

ltdiv id=loggtltdivgt

jQueryeach

A generic iterator funct ion which can be used to seamlessly iterate over both objects andarrays Arrays and array-like objects with a length property (such as a funct ions argumentsobject) are iterated by numeric index f rom 0 to length-1 Other objects are iterated via theirnamed propert ies

Added in version 10

jQueryeach(collect ion callback(indexInArray valueOfElement))Object

collect ionObject The object or array to iterate over

callback(indexInArrayvalueOfElement)Funct ion

The funct ion that will be executed on everyobject

The $each() funct ion is not the same as $(selector)each() which is used to iterate exclusivelyover a jQuery object The $each() funct ion can be used to iterate over any collect ion whetherit is a map (JavaScript object) or an array In the case of an array the callback is passed an arrayindex and a corresponding array value each t ime (The value can also be accessed through the

this keyword but Javascript will always wrap the this value as an Object even if it is a simplestring or number value) The method returns its f irst argument the object that was iterated

$each([52 97] function(index value) alert(index + + value) )

This produces two messages

0 52

1 97

If a map is used as the collect ion the callback is passed a key-value pair each t ime

var map = flammable inflammable duh no duh $each(map function(key value) alert(key + + value) )

Once again this produces two messages

f lammable inf lammable

duh no duh

We can break the $each() loop at a part icular iterat ion by making the callback funct ion returnfalse Returning non-false is the same as a cont inue statement in a for loop it will skipimmediately to the next iterat ion

Example 1 Iterates through the array displaying each number as both a word and numeral

Javascript

var arr = [ one two three four five ] var obj = one1 two2 three3 four4 five5

jQueryeach(arr function() $( + this)text(Mine is + this + ) return (this = three) wil l stop running after three )

jQueryeach(obj function(i val) $( + i)append(documentcreateTextNode( - + val)) )

CSS

div colorblue divfive colorred

HTML

ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt ltdiv id=fourgtltdivgt ltdiv id=fivegtltdivgt

Example 2 Iterates over items in an array accessing both the current item and its index

Javascript

$each( [abc] function(i l) alert( Index + i + + l ) )

Example 3 Iterates over the propert ies in an object accessing both the current item and its key

Javascript

$each( name John lang JS function(k v) alert( Key + k + Value + v ) )

jQueryboxModel

Deprecated in jQuery 13 (see jQuerysupport) States if the current page in the users browseris being rendered using the W3C CSS Box Model

Added in version 10

Example 1 Returns the box model for the if rame

Javascript

$(p)html(The box model for this iframe is ltspangt + jQueryboxModel + ltspangt)

CSS

p colorblue margin20px span colorred

HTML

ltpgt ltpgt

Example 2 Returns false if the page is in Quirks Mode in Internet Explorer

Javascript

$boxModel

Results

false

jQuerysupport

A collect ion of propert ies that represent the presence of dif ferent browser features or bugs

Added in version 13

Rather than using $browser to detect the current user agent and alter the page presentat ionbased on which browser is running it is a good pract ice to perform feature detect ion Thismeans that prior to execut ing code which relies on a browser feature we test to ensure thatthe feature works properly To make this process simpler jQuery performs many such tests andmakes the results available to us as propert ies of the jQuerysupport object

The values of all the support propert ies are determined using feature detect ion (and do notuse any form of browser snif f ing)

Following are a few resources that explain how feature detection works

httppetermichauxcaarticlesfeature-detection-state-of-the-art-browser-scripting

httpwwwjibberingcomfaqfaq_notesnot_browser_detecthtml

httpyurathinkweb2comcft

While jQuery includes a number of propert ies developers should feel f ree to add their own as

While jQuery includes a number of propert ies developers should feel f ree to add their own astheir needs dictate Many of the jQuerysupport propert ies are rather low-level so they aremost useful for plugin and jQuery core development rather than general day-to-daydevelopment Since jQuery requires these tests internally they must be performed on everypage load for that reason this list is kept short and limited to features needed by jQuery itself

The tests included in jQuerysupport are as follows

ajax is equal to t rue if a browser is able to create an XMLHttpRequest object

boxModel is equal to t rue if the page is rendering according to the W3C CSS Box Model(is current ly false in IE 6 and 7 when they are in Quirks Mode) This property is null unt ildocument ready occurs

changeBubbles is equal to t rue if the change event bubbles up the DOM tree asrequired by the W3C DOM event model (It is current ly false in IE and jQuery simulatesbubbling)

checkClone is equal to t rue if a browser correct ly clones the checked state of radiobuttons or checkboxes in document f ragments

checkOn is equal to t rue if the value of a checkbox defaults to on when no value isspecif ied

cors is equal to t rue if a browser can create an XMLHttpRequest object and if thatXMLHttpRequest object has a withCredent ials property To enable cross-domainrequests in environments that do not support cors yet but do allow cross-domain XHRrequests (windows gadget etc) set $support cors = t rue CORS WD

cssFloat is equal to t rue if the name of the property containing the CSS f loat value iscssFloat as def ined in the CSS Spec (It is current ly false in IE it uses styleFloat instead)

hrefNormalized is equal to t rue if the getAttribute() method retrieves the href at t ributeof elements unchanged rather than normalizing it to a fully-qualif ied URL (It is current lyfalse in IE the URLs are normalized)

htmlSerialize is equal to t rue if the browser is able to serializeinsert ltlinkgt elementsusing the innerHTML property of elements (is current ly false in IE)

leadingWhitespace is equal to t rue if the browser inserts content with innerHTMLexact ly as providedacirceurordquospecif ically if leading whitespace characters are preserved (It iscurrent ly false in IE 6-8)

noCloneChecked is equal to t rue if cloned DOM elements copy over the state of thechecked expando (It is current ly false in IE) (Added in jQuery 151)

noCloneEvent is equal to t rue if cloned DOM elements are created without eventhandlers (that is if the event handlers on the source element are not cloned) (It iscurrent ly false in IE)

opacity is equal to t rue if a browser can properly interpret the opacity style property (Itis current ly false in IE it uses alpha f ilters instead)

optDisabled is equal to t rue if opt ion elements within disabled select elements are notautomat ically marked as disabled

optSelected is equal to t rue if an ltopt iongt element that is selected by default has aworking selected property

scriptEval() is equal to t rue if inline scripts are automat ically evaluated and executedwhen inserted into the document using standard DOM manipulat ion methods such asappendChild() and createTextNode() (It is current ly false in IE it uses text to insertexecutable scripts)

Note No longer supported removed in jQuery 16 Prior to jQuery 151 the scriptEval()method was the stat ic scriptEval property The change to a method allowed the test tobe deferred unt il f irst use to prevent content security policy inline-script violat ions

style is equal to t rue if inline styles for an element can be accessed through the DOMattribute called style as required by the DOM Level 2 specif icat ion In this casegetAttribute(style) can retrieve this value in Internet Explorer cssText is used for thispurpose

submitBubbles is equal to t rue if the submit event bubbles up the DOM tree as requiredby the W3C DOM event model (It is current ly false in IE and jQuery simulates bubbling)

tbody is equal to t rue if an empty lttablegt element can exist without a lttbodygt elementAccording to the HTML specif icat ion this sub-element is opt ional so the property shouldbe true in a fully-compliant browser If false we must account for the possibility of thebrowser inject ing lttbodygt tags implicit ly (It is current ly false in IE which automat icallyinserts tbody if it is not present in a string assigned to innerHTML)

Example 1 Returns the box model for the if rame

Javascript

$(p)html(This frame uses the W3C box model ltspangt + jQuerysupportboxModel + ltspangt)

CSS

p colorblue margin20px span colorred

HTML

ltpgt ltpgt

Example 2 Returns false if the page is in QuirksMode in Internet Explorer

Javascript

jQuerysupportboxModel

Results

false

Plugin Authoring

  • JQuery Documentation
    • Core
      • jQueryholdReady
      • jQuerywhen
      • jQuerysub
      • jQuerynoConflict
      • jQuery
        • Selector Context
        • Using DOM elements
        • Cloning jQuery Objects
        • Returning an Empty Set
          • jQuery
            • Creating New Elements
              • jQuery
                • Selectors
                  • focus $(focus)
                  • selected $(selected)
                  • checked $(checked)
                  • disabled $(disabled)
                  • enabled $(enabled)
                  • file $(file)
                  • button $(button)
                  • reset $(reset)
                  • image $(image)
                  • submit $(submit)
                  • checkbox $(checkbox)
                  • radio $(radio)
                  • password $(password)
                  • text $(text)
                  • input $(input)
                  • only-child $(only-child)
                  • last-child $(last-child)
                  • first-child $(first-child)
                  • nth-child $(nth-child(indexevenoddequation))
                  • attributeContainsPrefix $([attribute|=value])
                  • attributeContainsWord $([attribute~=value])
                  • attributeMultiple $([attributeFilter1][attributeFilter2][attributeFilterN])
                  • attributeContains $([attribute=value])
                  • attributeEndsWith $([attribute$=value])
                  • attributeStartsWith $([attribute^=value])
                  • attributeNotEqual $([attribute=value])
                  • attributeEquals $([attribute=value])
                  • attributeHas $([attribute])
                  • visible $(visible)
                  • hidden $(hidden)
                  • parent $(parent)
                  • has $(has(selector))
                  • empty $(empty)
                  • contains $(contains(text))
                  • animated $(animated)
                  • header $(header)
                  • lt $(lt(index))
                  • gt $(gt(index))
                  • eq $(eq(index))
                  • odd $(odd)
                  • even $(even)
                  • not $(not(selector))
                  • Additional Notes
                  • last $(last)
                  • first $(first)
                  • next siblings $(prev ~ siblings)
                  • next adjacent $(prev + next)
                  • child $(parent gt child)
                  • descendant $(ancestor descendant)
                  • multiple $(selector1 selector2 selectorN)
                  • all $()
                  • class $(class)
                  • element $(element)
                  • id $(id)
                    • Traversing
                      • has
                      • parentsUntil
                      • prevUntil
                      • nextUntil
                      • each
                      • first
                      • last
                      • slice
                        • Negative Indices
                          • end
                          • andSelf
                          • siblings
                          • prevAll
                          • prev
                          • parents
                          • parent
                          • offsetParent
                          • nextAll
                          • next
                          • find
                          • contents
                          • closest
                          • closest
                          • children
                          • add
                          • not
                            • Removing Specific Elements
                              • map
                              • is
                                • Using a Function
                                  • eq
                                  • filter
                                    • Using a Filter Function
                                        • Attributes
                                          • removeProp
                                          • prop
                                          • prop
                                            • Computed property values
                                              • val
                                              • val
                                              • html
                                              • html
                                              • toggleClass
                                              • removeClass
                                              • hasClass
                                              • removeAttr
                                              • attr
                                              • attr
                                                • Setting a simple attribute
                                                • Setting several attributes at once
                                                • Computed attribute values
                                                  • addClass
                                                    • CSS
                                                      • jQuerycssHooks
                                                        • Feature Testing
                                                        • Defining a complete cssHook
                                                        • Special units
                                                        • Animating with cssHooks
                                                          • outerWidth
                                                          • outerHeight
                                                          • innerWidth
                                                          • innerHeight
                                                          • width
                                                          • width
                                                          • height
                                                          • height
                                                          • scrollLeft
                                                          • scrollLeft
                                                          • scrollTop
                                                          • scrollTop
                                                          • position
                                                          • offset
                                                          • offset
                                                          • css
                                                          • css
                                                          • toggleClass see Attributes
                                                          • removeClass see Attributes
                                                          • hasClass see Attributes
                                                          • addClass see Attributes
                                                            • Manipulation
                                                              • removeProp see Attributes
                                                              • prop see Attributes
                                                              • prop see Attributes
                                                              • outerWidth see CSS
                                                              • outerHeight see CSS
                                                              • innerWidth see CSS
                                                              • innerHeight see CSS
                                                              • width see CSS
                                                              • width see CSS
                                                              • height see CSS
                                                              • height see CSS
                                                              • scrollLeft see CSS
                                                              • scrollLeft see CSS
                                                              • scrollTop see CSS
                                                              • scrollTop see CSS
                                                              • position see CSS
                                                              • offset see CSS
                                                              • offset see CSS
                                                              • css see CSS
                                                              • css see CSS
                                                              • unwrap
                                                              • detach
                                                              • clone
                                                              • remove
                                                              • empty
                                                              • replaceAll
                                                              • replaceWith
                                                              • wrapInner
                                                              • wrapAll
                                                              • wrap
                                                              • insertBefore
                                                              • before
                                                                • Additional Arguments
                                                                  • insertAfter
                                                                  • after
                                                                    • Inserting Disconnected DOM nodes
                                                                    • Passing a Function
                                                                    • Additional Arguments
                                                                      • prependTo
                                                                      • prepend
                                                                        • Additional Arguments
                                                                          • appendTo
                                                                          • append
                                                                            • Additional Arguments
                                                                              • val see Attributes
                                                                              • val see Attributes
                                                                              • text
                                                                              • text
                                                                              • html see Attributes
                                                                              • html see Attributes
                                                                              • toggleClass see Attributes
                                                                              • removeClass see Attributes
                                                                              • hasClass see Attributes
                                                                              • removeAttr see Attributes
                                                                              • attr see Attributes
                                                                              • attr see Attributes
                                                                              • addClass see Attributes
                                                                                • Data
                                                                                  • jQueryhasData
                                                                                  • jQueryremoveData
                                                                                  • jQuerydata
                                                                                  • jQuerydata
                                                                                  • jQuerydequeue
                                                                                  • jQueryqueue
                                                                                  • jQueryqueue
                                                                                  • clearQueue
                                                                                  • removeData
                                                                                  • data
                                                                                  • data
                                                                                  • dequeue
                                                                                  • queue
                                                                                  • queue
                                                                                    • Forms
                                                                                      • submit
                                                                                      • select
                                                                                      • change
                                                                                      • blur
                                                                                      • focus
                                                                                      • serializeArray
                                                                                      • serialize
                                                                                      • jQueryparam
                                                                                      • val see Attributes
                                                                                      • val see Attributes
                                                                                        • Events
                                                                                          • toggle
                                                                                          • eventnamespace
                                                                                          • undelegate
                                                                                          • delegate
                                                                                          • jQueryproxy
                                                                                          • focusout
                                                                                          • focusin
                                                                                          • eventisImmediatePropagationStopped
                                                                                          • eventstopImmediatePropagation
                                                                                          • eventisPropagationStopped
                                                                                          • eventstopPropagation
                                                                                          • eventisDefaultPrevented
                                                                                          • eventpreventDefault
                                                                                          • eventtimeStamp
                                                                                          • eventresult
                                                                                          • eventwhich
                                                                                          • eventpageY
                                                                                          • eventpageX
                                                                                          • eventcurrentTarget
                                                                                          • eventrelatedTarget
                                                                                          • eventdata
                                                                                          • eventtarget
                                                                                          • eventtype
                                                                                          • keydown
                                                                                          • scroll
                                                                                          • resize
                                                                                          • keyup
                                                                                          • keypress
                                                                                          • submit see Forms
                                                                                          • select see Forms
                                                                                          • change see Forms
                                                                                          • blur see Forms
                                                                                          • focus see Forms
                                                                                          • mousemove
                                                                                          • hover
                                                                                          • hover
                                                                                          • mouseleave
                                                                                          • mouseenter
                                                                                          • mouseout
                                                                                          • mouseover
                                                                                          • dblclick
                                                                                          • click
                                                                                          • mouseup
                                                                                          • mousedown
                                                                                          • error
                                                                                          • unload
                                                                                          • load
                                                                                          • ready
                                                                                            • Aliasing the jQuery Namespace
                                                                                              • die
                                                                                              • die
                                                                                              • live
                                                                                                • Event Delegation
                                                                                                • Multiple Events
                                                                                                • Event Data
                                                                                                • Event Context
                                                                                                • Caveats
                                                                                                  • triggerHandler
                                                                                                  • trigger
                                                                                                  • one
                                                                                                  • unbind
                                                                                                    • Using Namespaces
                                                                                                    • Using the Event Object
                                                                                                      • bind
                                                                                                        • Multiple Events
                                                                                                        • Event Handlers
                                                                                                        • The Event object
                                                                                                        • Passing Event Data
                                                                                                            • Deferred Object
                                                                                                              • deferredpipe
                                                                                                              • deferredalways
                                                                                                              • promise
                                                                                                              • deferredpromise
                                                                                                              • jQuerywhen see Core
                                                                                                              • deferredresolveWith
                                                                                                              • deferredrejectWith
                                                                                                              • deferredfail
                                                                                                              • deferreddone
                                                                                                              • deferredthen
                                                                                                              • deferredreject
                                                                                                              • deferredisRejected
                                                                                                              • deferredisResolved
                                                                                                              • deferredresolve
                                                                                                                • Effects
                                                                                                                  • fadeToggle
                                                                                                                    • Easing
                                                                                                                    • Callback Function
                                                                                                                      • jQueryfxinterval
                                                                                                                      • delay
                                                                                                                      • jQueryfxoff
                                                                                                                      • clearQueue see Data
                                                                                                                      • dequeue see Data
                                                                                                                      • queue see Data
                                                                                                                      • queue see Data
                                                                                                                      • stop
                                                                                                                      • animate
                                                                                                                        • Animation Properties and Values
                                                                                                                        • Duration
                                                                                                                        • Complete Function
                                                                                                                        • Basic Usage
                                                                                                                        • Step Function
                                                                                                                        • Easing
                                                                                                                        • Per-property Easing
                                                                                                                          • fadeTo
                                                                                                                          • fadeOut
                                                                                                                            • Easing
                                                                                                                            • Callback Function
                                                                                                                              • fadeIn
                                                                                                                                • Easing
                                                                                                                                • Callback Function
                                                                                                                                  • slideToggle
                                                                                                                                    • Easing
                                                                                                                                    • Callback Function
                                                                                                                                      • slideUp
                                                                                                                                        • Easing
                                                                                                                                        • Callback Function
                                                                                                                                          • slideDown
                                                                                                                                            • Easing
                                                                                                                                            • Callback Function
                                                                                                                                              • toggle
                                                                                                                                              • hide
                                                                                                                                              • show
                                                                                                                                                • Ajax
                                                                                                                                                  • jQueryajaxPrefilter
                                                                                                                                                  • ajaxComplete
                                                                                                                                                  • serializeArray see Forms
                                                                                                                                                  • serialize see Forms
                                                                                                                                                  • jQueryajaxSetup
                                                                                                                                                  • ajaxSuccess
                                                                                                                                                  • ajaxStop
                                                                                                                                                  • ajaxStart
                                                                                                                                                  • ajaxSend
                                                                                                                                                  • ajaxError
                                                                                                                                                  • jQuerypost
                                                                                                                                                    • The jqXHR Object
                                                                                                                                                      • jQuerygetScript
                                                                                                                                                      • jQuerygetJSON
                                                                                                                                                        • JSONP
                                                                                                                                                        • The jqXHR Object
                                                                                                                                                          • jQueryget
                                                                                                                                                            • The jqXHR Object
                                                                                                                                                              • load
                                                                                                                                                                • Loading Page Fragments
                                                                                                                                                                  • jQueryajax
                                                                                                                                                                    • The jqXHR Object
                                                                                                                                                                    • Callback Function Queues
                                                                                                                                                                    • Data Types
                                                                                                                                                                    • Sending Data to the Server
                                                                                                                                                                    • Advanced Options
                                                                                                                                                                    • Extending Ajax
                                                                                                                                                                      • jQueryparam see Forms
                                                                                                                                                                        • Miscellaneous
                                                                                                                                                                          • each see Traversing
                                                                                                                                                                          • toArray
                                                                                                                                                                          • index
                                                                                                                                                                            • Return Values
                                                                                                                                                                            • Detail
                                                                                                                                                                              • removeData see Data
                                                                                                                                                                              • data see Data
                                                                                                                                                                              • data see Data
                                                                                                                                                                              • get
                                                                                                                                                                              • size
                                                                                                                                                                              • jQuerynoConflict see Core
                                                                                                                                                                              • jQueryparam see Forms
                                                                                                                                                                                • Dimensions
                                                                                                                                                                                  • outerWidth see CSS
                                                                                                                                                                                  • outerHeight see CSS
                                                                                                                                                                                  • innerWidth see CSS
                                                                                                                                                                                  • innerHeight see CSS
                                                                                                                                                                                  • width see CSS
                                                                                                                                                                                  • width see CSS
                                                                                                                                                                                  • height see CSS
                                                                                                                                                                                  • height see CSS
                                                                                                                                                                                    • Offset
                                                                                                                                                                                      • offsetParent see Traversing
                                                                                                                                                                                      • scrollLeft see CSS
                                                                                                                                                                                      • scrollLeft see CSS
                                                                                                                                                                                      • scrollTop see CSS
                                                                                                                                                                                      • scrollTop see CSS
                                                                                                                                                                                      • position see CSS
                                                                                                                                                                                      • offset see CSS
                                                                                                                                                                                      • offset see CSS
                                                                                                                                                                                        • Utilities
                                                                                                                                                                                          • jQuerynow
                                                                                                                                                                                          • jQueryparseXML
                                                                                                                                                                                          • jQuerytype
                                                                                                                                                                                          • jQueryisWindow
                                                                                                                                                                                          • jQueryparseJSON
                                                                                                                                                                                          • jQueryproxy see Events
                                                                                                                                                                                          • jQuerycontains
                                                                                                                                                                                          • jQuerynoop
                                                                                                                                                                                          • jQueryglobalEval
                                                                                                                                                                                          • jQueryisXMLDoc
                                                                                                                                                                                          • jQueryremoveData see Data
                                                                                                                                                                                          • jQuerydata see Data
                                                                                                                                                                                          • jQuerydata see Data
                                                                                                                                                                                          • jQuerydequeue see Data
                                                                                                                                                                                          • jQueryqueue see Data
                                                                                                                                                                                          • jQueryqueue see Data
                                                                                                                                                                                          • clearQueue see Data
                                                                                                                                                                                          • jQueryisEmptyObject
                                                                                                                                                                                          • jQueryisPlainObject
                                                                                                                                                                                          • dequeue see Data
                                                                                                                                                                                          • queue see Data
                                                                                                                                                                                          • queue see Data
                                                                                                                                                                                          • jQuerybrowser
                                                                                                                                                                                          • jQuerybrowserversion
                                                                                                                                                                                          • jQuerytrim
                                                                                                                                                                                          • jQueryisFunction
                                                                                                                                                                                          • jQueryisArray
                                                                                                                                                                                          • jQueryunique
                                                                                                                                                                                          • jQuerymerge
                                                                                                                                                                                          • jQueryinArray
                                                                                                                                                                                          • jQuerymap
                                                                                                                                                                                          • jQuerymakeArray
                                                                                                                                                                                          • jQuerygrep
                                                                                                                                                                                          • jQueryextend
                                                                                                                                                                                          • jQueryeach
                                                                                                                                                                                          • jQueryboxModel
                                                                                                                                                                                          • jQuerysupport
                                                                                                                                                                                            • Plugin Authoring

    jQuerywhen(deferreds)Promise

    deferredsDeferred One or more Deferred objects or plain JavaScript objects

    If a single Deferred is passed to jQuerywhen its Promise object (a subset of the Deferredmethods) is returned by the method Addit ional methods of the Promise object can be called toattach callbacks such as deferredthen When the Deferred is resolved or rejected usually bythe code that created the Deferred originally the appropriate callbacks will be called Forexample the jqXHR object returned by jQueryajax is a Deferred and can be used this way

    $when( $ajax(testaspx) )then(function(ajaxArgs) alert(ajaxArgs[1]) ajaxArgs is [ success statusText jqXHR ] )

    If a single argument is passed to jQuerywhen and it is not a Deferred it will be t reated as aresolved Deferred and any doneCallbacks at tached will be executed immediately ThedoneCallbacks are passed the original argument In this case any failCallbacks you might set arenever called since the Deferred is never rejected For example

    $when( testing 123 )done( function(x) alert(xtesting) alerts 123 )

    In the case where mult iple Deferred objects are passed to jQuerywhen the method returns thePromise from a new master Deferred object that t racks the aggregate state of all theDeferreds it has been passed The method will resolve its master Deferred as soon as all theDeferreds resolve or reject the master Deferred as soon as one of the Deferreds is rejected Ifthe master Deferred is resolved it is passed the resolved values of all the Deferreds that werepassed to jQuerywhen For example when the Deferreds are jQueryajax() requests thearguments will be the jqXHR objects for the requests in the order they were given in theargument list

    In the mult iple-Deferreds case where one of the Deferreds is rejected jQuerywhen immediatelyf ires the failCallbacks for its master Deferred Note that some of the Deferreds may st ill beunresolved at that point If you need to perform addit ional processing for this case such ascanceling any unf inished ajax requests you can keep references to the underlying jqXHRobjects in a closure and inspectcancel them in the failCallback

    Example 1 Execute a funct ion af ter two ajax requests are successful (See the jQueryajax()documentat ion for a complete descript ion of success and error cases for an ajax request)

    Javascript

    $when($ajax(page1php) $ajax(page2php))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 ] i f ( Whip Ittest(jqXHRresponseText) ) alert(First page has Whip It somewhere) )

    Example 2 Execute the funct ion myFunc when both ajax requests are successful or myFailureif either one has an error

    Javascript

    $when($ajax(page1php) $ajax(page2php)) then(myFunc myFailure)

    jQuerysub

    Creates a new copy of jQuery whose propert ies and methods can be modif ied withoutaf fect ing the original jQuery object

    Added in version 15

    jQuerysub()jQuery

    There are two specif ic use cases for which jQuerysub() was created The f irst was for providinga painless way of overriding jQuery methods without completely destroying the originalmethods and another was for helping to do encapsulat ion and basic namespacing for jQueryplugins

    Note that jQuerysub() doesnt at tempt to do any sort of isolat ion - that s not its intent ion Allthe methods on the subd version of jQuery will st ill point to the original jQuery (events boundand triggered will st ill be through the main jQuery data will be bound to elements through themain jQuery Ajax queries and events will run through the main jQuery etc)

    Note that if youre looking to use this for plugin development you should f irst strongly considerusing something like the jQuery UI widget factory which manages both state and plugin sub-methods Some examples of using the jQuery UI widget factory to build a plugin

    The part icular use cases of this method can be best described through some examples

    Example 1 Adding a method to a jQuery sub so that it isnt exposed externally

    Javascript

    (function() var sub$ = jQuerysub()

    sub$fnmyCustomMethod = function() return just for me

    sub$(document)ready(function() sub$(body)myCustomMethod() just for me ) )() typeof jQuery(body)myCustomMethod undefined

    Example 2 Override some jQuery methods to provide new funct ionality

    Javascript

    (function() var myjQuery = jQuerysub()

    myjQueryfnremove = function() New functionality Trigger a remove event thistrigger(remove)

    Be sure to call the original jQuery remove method return jQueryfnremoveapply( this arguments )

    myjQuery(function($) $(menu)cl ick(function() $(this)find(submenu)remove() )

    A new remove event is now triggered from this copy of jQuery $(document)bind(remove function(e) $(etarget)parent()hide() ) ))()

    Regular jQuery doesnt trigger a remove event when removing an element This functionality is only contained within the modified myjQuery

    Example 3 Create a plugin that returns plugin-specif ic methods

    Javascript

    (function() Create a new copy of jQuery using sub() var plugin = jQuerysub()

    Extend that copy with the new plugin methods pluginfnextend( open function() return thisshow() close function() return thishide() )

    Add our plugin to the original jQuery jQueryfnmyplugin = function() thisaddClass(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 Call ing just $(main)open() wont work as open doesnt exist)

    jQuerynoConflict

    Relinquish jQuerys control of the $ variable

    Added in version 10

    jQuerynoConf lict (removeAll)Object

    removeAllBoolean (opt ional) A Boolean indicat ing whether to remove all jQueryvariables f rom the global scope (including jQuery itself )

    Many JavaScript libraries use $ as a funct ion or variable name just as jQuery does In jQueryscase $ is just an alias for jQuery so all funct ionality is available without using $ If we need touse another JavaScript library alongside jQuery we can return control of $ back to the otherlibrary with a call to $noConf lict ()

    ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() Code that uses other l ibrarys $ can follow hereltscriptgt

    This technique is especially ef fect ive in conjunct ion with the ready() methods ability to aliasthe jQuery object as within callback passed to ready() we can use $ if we wish without fear ofconf licts later

    ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() jQuery(document)ready(function($) Code that uses jQuerys $ can follow here ) Code that uses other l ibrarys $ can follow hereltscriptgt

    If necessary we can free up the jQuery name as well by passing true as an argument to themethod This is rarely necessary and if we must do this (for example if we need to use mult ipleversions of the jQuery library on the same page) we need to consider that most plug-ins relyon the presence of the jQuery variable and may not operate correct ly in this situat ion

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

    Javascript

    jQuerynoConfl ict() Do something with jQueryjQuery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

    Example 2 Reverts the $ alias and then creates and executes a funct ion to provide the $ as ajQuery alias inside the funct ions scope Inside the funct ion the original $ object is not availableThis works well for most plugins that dont rely on any other library

    Javascript

    jQuerynoConfl ict()(function($) $(function() more code using $ as alias to jQuery ))(jQuery) other code using $ as an alias to the other l ibrary

    Example 3 You can chain the jQuerynoConf lict () with the shorthand ready for a compact code

    Javascript

    jQuerynoConfl ict()(function() code using jQuery) other code using $ as an alias to the other l ibrary

    Example 4 Creates a dif ferent alias instead of jQuery to use in the rest of the script

    Javascript

    var j = jQuerynoConfl ict() Do something with jQueryj(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

    Example 5 Completely move jQuery to a new namespace in another object

    Javascript

    var dom = domquery = jQuerynoConfl ict(true)

    Results

    Do something with the new jQuerydomquery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none Do something with another version of jQueryjQuery(div gt p)hide()

    jQuery

    Accepts a string containing a CSS selector which is then used to match a set of elements

    Added in version 14

    jQuery()jQuery

    In the f irst formulat ion listed above jQuery() acirceurordquo which can also be writ ten as $() acirceurordquo searchesthrough the DOM for any elements that match the provided selector and creates a new jQueryobject that references these elements

    $(divfoo)

    Selector Context

    By default selectors perform their searches within the DOM start ing at the document rootHowever an alternate context can be given for the search by using the opt ional secondparameter to the $() funct ion For example to do a search within an event handler the searchcan be restricted like so

    $(divfoo)cl ick(function() $(span this)addClass(bar))

    When the search for the span selector is restricted to the context of this only spans within theclicked element will get the addit ional class

    Internally selector context is implemented with the f ind() method so $(span this) is equivalentto $(this)f ind(span)

    Using DOM elements

    The second and third formulat ions of this funct ion create a jQuery object using one or moreDOM elements that were already selected in some other way A common use of this facility isto call jQuery methods on an element that has been passed to a callback funct ion through thekeyword this

    $(divfoo)cl ick(function() $(this)sl ideUp())

    This example causes elements to be hidden with a sliding animat ion when clicked Because thehandler receives the clicked item in the this keyword as a bare DOM element the element mustbe passed to the $() funct ion before applying jQuery methods to it

    XML data returned from an Ajax call can be passed to the $() funct ion so individual elements of

    the XML structure can be retrieved using f ind() and other DOM traversal methods

    $post(urlxml function(data) var $child = $(data)find(child))

    Cloning jQuery Objects

    When a jQuery object is passed to the $() funct ion a clone of the object is created This newjQuery object references the same DOM elements as the init ial one

    Returning an Empty Set

    As of jQuery 14 calling the jQuery() method with no arguments returns an empty jQuery set(with a length property of 0) In previous versions of jQuery this would return a set containingthe document node

    Example 1 Find all p elements that are children of a div element and apply a border to them

    Javascript

    $(div gt p)css(border 1px solid gray)

    HTML

    ltpgtoneltpgt ltdivgtltpgttwoltpgtltdivgt ltpgtthreeltpgt

    Example 2 Find all inputs of type radio within the f irst form in the document

    Javascript

    $(inputradio documentforms[0])

    Example 3 Find all div elements within an XML document f rom an Ajax response

    Javascript

    $(div xmlresponseXML)

    Example 4 Set the background color of the page to black

    Javascript

    $(documentbody)css( background black )

    Example 5 Hide all the input elements within a form

    Javascript

    $(myFormelements)hide()

    jQuery

    Creates DOM elements on the f ly f rom the provided string of raw HTML

    Added in version 14

    jQuery(html props)jQuery

    htmlString A string def ining a single standalone HTML element (eg ltdivgt orltdivgtltdivgt)

    propsObject An map of at t ributes events and methods to call on the newly-createdelement

    Creating New Elements

    If a string is passed as the parameter to $() jQuery examines the string to see if it looks likeHTML (ie it has lttag gt somewhere within the string) If not the string is interpreted as aselector expression as explained above But if the string appears to be an HTML snippetjQuery at tempts to create new DOM elements as described by the HTML Then a jQuery objectis created and returned that refers to these elements You can perform any of the usual jQuerymethods on this object

    $(ltp id=testgtMy ltemgtnewltemgt textltpgt)appendTo(body)

    If the HTML is more complex than a single tag without at t ributes as it is in the above examplethe actual creat ion of the elements is handled by the browsers innerHTML mechanism In mostcases jQuery creates a new

    element and sets the innerHTML property of the element to the HTML snippet that was passedin When the parameter has a single tag such as$(ltimgAcirc gt) or $(ltagtltagt) jQuery creates the element using the nat ive JavaScriptcreateElement() funct ion

    When passing in complex HTML some browsers may not generate a DOM that exact ly

    replicates the HTML source provided As ment ioned we use the browsers innerHTML propertyto parse the passed HTML and insert it into the current document During this process somebrowsers f ilter out certain elements such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements inserted may not be representat ive of the original string passed

    Filtering isnt however just limited to these tags For example Internet Explorer prior to version 8will also convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

    To ensure cross-plat form compat ibility the snippet must be well-formed Tags that can containother elements should be paired with a closing tag

    $(lta href=httpjquerycomgtltagt)

    Alternat ively jQuery allows XML-like tag syntax (with or without a space before the slash)

    $(ltagt)

    Tags that cannot contain elements may be quick-closed or not

    $(ltimg gt)$(ltinputgt)

    When passing HTML to jQuery() please also note that text nodes are not t reated as DOMelements With the except ion of a few methods (such as content()) they are generallyotherwise ignored or removed Eg

    var el = $(1ltbrgt2ltbrgt3) returns [ltbrgt 2 ltbrgt] el = $(1ltbrgt2ltbrgt3 gt) returns [ltbrgt 2 ltbrgt 3 ampgt]

    This behaviour is expected

    As of jQuery 14 the second argument to jQuery() can accept a map consist ing of a supersetof the propert ies that can be passed to the at t r() method Furthermore any event type can bepassed in and the following jQuery methods can be called val css html text data widthheight or of fset The name class must be quoted in the map since it is a JavaScript reservedword and className cannot be used since it is not the correct at t ribute name

    Note Internet Explorer will not allow you to create an input or button element and change itstype you must specify the type using ltinput type=checkbox gt for example A demonstrat ionof this can be seen below

    Unsupported in IE

    $(ltinput gt type text name test)appendTo(body)

    Supported workaround

    $(ltinput type=text gt)attr( name test)appendTo(body)

    Example 1 Create a div element (and all of its contents) dynamically and append it to the bodyelement Internally an element is created and its innerHTML property set to the given markup

    Javascript

    $(ltdivgtltpgtHelloltpgtltdivgt)appendTo(body)

    Example 2 Create some DOM elements

    Javascript

    $(ltdivgt class test text Click me cl ick function() $(this)toggleClass(test) )appendTo(body)

    jQuery

    Binds a funct ion to be executed when the DOM has f inished loading

    Added in version 10

    jQuery(callback)jQuery

    callbackFunct ion The funct ion to execute when the DOM is ready

    This funct ion behaves just like $(document)ready() in that it should be used to wrap other $()operat ions on your page that depend on the DOM being ready While this funct ion is

    technically chainable there really isnt much use for chaining against it

    Example 1 Execute the funct ion when the DOM is ready to be used

    Javascript

    $(function() Document is ready )

    Example 2 Use both the shortcut for $(document)ready() and the argument to write failsafejQuery code using the $ alias without relying on the global alias

    Javascript

    jQuery(function($) Your code using failsafe $ alias here )

    Selectors

    focus $(focus)

    Selects element if it is current ly focused

    Added in version 16

    $(focus)

    As with other pseudo-class selectors (those that begin with a ) it is recommended toprecede focus with a tag name or some other selector otherwise the universal selector () isimplied In other words the bare $(focus) is equivalent to $(focus) If you are looking for thecurrent ly focused element $( documentact iveElement ) will retrieve it without having to searchthe whole DOM tree

    Example 1 Adds the focused class to whatever element has focus

    Javascript

    $()l ive(focus blur function(e) var el = $(this) setTimeout(function() eltoggleClass(focused elis(focus)) 0))

    CSS

    focused background abcdef

    HTML

    ltinput tabIndex=1gtltinput tabIndex=2gtltselect tabIndex=3gt ltoptiongtselect menultoptiongtltselectgtltdiv tabIndex=4gt a divltdivgt

    selected $(selected)

    Selects all elements that are selected

    Added in version 10

    $(selected)

    The selected selector works for ltopt iongt elements It does not work for checkboxes or radioinputs use checked for them

    Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

    Javascript

    $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) trigger(change)

    CSS

    div colorred

    HTML

    ltselect name=garden multiple=multiplegt

    ltoptiongtFlowersltoptiongt ltoption selected=selectedgtShrubsltoptiongt ltoptiongtTreesltoptiongt ltoption selected=selectedgtBushesltoptiongt

    ltoptiongtGrassltoptiongt ltoptiongtDirtltoptiongt ltselectgt ltdivgtltdivgt

    checked $(checked)

    Matches all elements that are checked

    Added in version 10

    $(checked)

    The checked selector works for checkboxes and radio buttons For select elements use theselected selector

    Example 1 Finds all input elements that are checked

    Javascript

    function countChecked() var n = $(inputchecked)length $(div)text(n + (n lt= 1 is are) + checked)countChecked()$(checkbox)cl ick(countChecked)

    CSS

    div colorred

    HTML

    ltformgt ltpgt ltinput type=checkbox name=newsletter checked=checked value=Hourly gt

    ltinput type=checkbox name=newsletter value=Daily gt ltinput type=checkbox name=newsletter value=Weekly gt

    ltinput type=checkbox name=newsletter checked=checked value=Monthly gt ltinput type=checkbox name=newsletter value=Yearly gt ltpgtltformgtltdivgtltdivgt

    Example 2

    Javascript

    $(input)cl ick(function() $(log)html( $(checked)val() + is checked ))

    CSS

    input label l ine-height 15em

    HTML

    ltformgt ltdivgt ltinput type=radio name=fruit value=orange id=orangegt ltlabel for=orangegtorangeltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=apple id=applegt ltlabel for=applegtappleltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=banana id=bananagt ltlabel for=bananagtbananaltlabelgt ltdivgt ltdiv id=loggtltdivgtltformgt

    disabled $(disabled)

    Selects all elements that are disabled

    Added in version 10

    $(disabled)

    As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(disabled) is equivalent to $(disabled) so $(inputdisabled) should beused instead

    Example 1 Finds all input elements that are disabled

    Javascript

    $(inputdisabled)val(this is it)

    HTML

    ltformgt

    ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

    enabled $(enabled)

    Selects all elements that are enabled

    Added in version 10

    $(enabled)

    As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(enabled) is equivalent to $(enabled) so $(inputenabled) should beused instead

    Example 1 Finds all input elements that are enabled

    Javascript

    $(inputenabled)val(this is it)

    HTML

    ltformgt

    ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

    file $(file)

    Selects all elements of type f ile

    Added in version 10

    $(f ile)

    f ile is equivalent to [type=f ile] 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 theuniversal selector () is implied In other words the bare $(f ile) is equivalent to $(f ile) so$(inputf ile) should be used instead

    Example 1 Finds all f ile inputs

    Javascript

    var input = $(inputfi le)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height45px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    button $(button)

    Selects all but ton elements and elements of type button

    Added in version 10

    $(button)

    Example 1 Finds all but ton inputs

    Javascript

    var input = $(button)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height45px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    reset $(reset)

    Selects all elements of type reset

    Added in version 10

    $(reset)

    reset is equivalent to [type=reset]

    Example 1 Finds all reset inputs

    Javascript

    var input = $(inputreset)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height45px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    image $(image)

    Selects all elements of type image

    Added in version 10

    $(image)

    image is equivalent to [type=image]

    Example 1 Finds all image inputs

    Javascript

    var input = $(inputimage)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height45px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    submit $(submit)

    Selects all elements of type submit

    Added in version 10

    $(submit)

    The submit selector typically applies to button or input elements Note that some browserstreat ltbuttongt element as type=default implicit ly while others (such as Internet Explorer) donot

    Example 1 Finds all submit elements that are descendants of a td element

    Javascript

    var submitEl = $(td submit) parent(td) css(backgroundyellow border3px red solid) end() $(result)text( jQuery matched + submitEllength + elements)

    so it wont 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 = inputElattr(type) type= + inputElattr(type) + $(el)before(lttdgt + inputEl[0]nodeName + inputType + lttdgt) )

    CSS

    textarea height45px

    HTML

    lttablegtltformgtlttable id=exampleTable border=1 cellpadding=10 align=centergt

    lttrgt ltthgt Element Type ltthgt ltthgt Element ltthgt

    lttr lttrgt lttdgt ltinput type=button value=Input Buttongt lttdgt

    lttrgt lttrgt lttdgt ltinput type=checkbox gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=fi le gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=hidden gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=image gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=password gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=radio gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=reset gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=submit gt lttdgt

    lttrgt lttrgt lttdgt ltinput type=text gt lttdgt

    lttrgt lttrgt lttdgt ltselectgtltoptiongtOptionltoptiongtltselectgt lttdgt

    lttrgt lttrgt lttdgt lttextareagtlttextareagt lttdgt lttrgt

    lttrgt lttdgt ltbuttongtButtonltbuttongt lttdgt lttrgt lttrgt lttdgt ltbutton type=submitgtButton type=submitltbuttongt lttdgt lttrgt

    lttablegtltformgtltdiv id=resultgtltdivgt

    checkbox $(checkbox)

    Selects all elements of type checkbox

    Added in version 10

    $(checkbox)

    $(checkbox) is equivalent to $([type=checkbox]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(checkbox) isequivalent to $(checkbox) so $(inputcheckbox) should be used instead

    Example 1 Finds all checkbox inputs

    Javascript

    var input = $(form inputcheckbox)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height25px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=checkbox gt ltinput type=fi le gt ltinput type=hidden gt

    ltinput type=image gt ltinput type=password gt ltinput type=radio gt

    ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

    ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

    ltdivgt ltdivgt

    radio $(radio)

    Selects all elements of type radio

    Added in version 10

    $(radio)

    $(radio) is equivalent to $([type=radio]) As with other pseudo-class selectors (those thatbegin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(radio) is equivalentto $(radio) so $(inputradio) should be used instead

    To select a set of associated radio buttons you might use $(input[name=gender]radio)

    Example 1 Finds all radio inputs

    Javascript

    var input = $(form inputradio)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height25px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio name=asdf gt ltinput type=radio name=asdf gt

    ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

    ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

    ltdivgt ltdivgt

    password $(password)

    Selects all elements of type password

    Added in version 10

    $(password)

    $(password) is equivalent to $([type=password]) As with other pseudo-class selectors (thosethat 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 $(password) isequivalent to $(password) so $(inputpassword) should be used instead

    Example 1 Finds all password inputs

    Javascript

    var input = $(inputpassword)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height45px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    text $(text)

    Selects all elements of type text

    Added in version 10

    $(text)

    $(text ) is equivalent to $([type=text ]) and thus selects all ltinput type=textgt elements Aswith other pseudo-class selectors (those that begin with a ) it is recommended to precede itwith a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(text ) is equivalent to $(text ) so $(inputtext ) should be usedinstead

    Note As of jQuery 152 text selects input elements that have no specif ied type at t ribute (inwhich case type=text is implied)

    Example 1 Finds all text inputs

    Javascript

    var input = $(form inputtext)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

    CSS

    textarea height25px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

    input $(input)

    Selects all input textarea select and button elements

    Added in version 10

    $(input)

    The input selector basically selects all form controls

    Example 1 Finds all input elements

    Javascript

    var all Inputs = $(input) var formChildren = $(form gt ) $(messages)text(Found + all Inputslength + inputs and the form has + formChildrenlength + children) so it wont submit $(form)submit(function () return false )

    CSS

    textarea height25px

    HTML

    ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

    ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

    ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

    ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

    lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdiv id=messagesgt ltdivgt

    only-child $(only-child)

    Selects all elements that are the only child of their parent

    Added in version 114

    $(only-child)

    If the parent has other child elements nothing is matched

    Example 1 Change the text and add a border for each button that is the only child of its parent

    Javascript

    $(div buttononly-child)text(Alone)css(border 2px blue solid)

    CSS

    div width100px height80px margin5px floatleft backgroundb9e

    HTML

    ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongtltdivgt

    ltdivgt ltbuttongtSiblingltbuttongtltdivgtltdivgt Noneltdivgt

    ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt

    ltdivgtltdivgt ltbuttongtSiblingltbuttongtltdivgt

    last-child $(last-child)

    Selects all elements that are the last child of their parent

    Added in version 114

    $(last-child)

    While last matches only a single element last-child can match more than one one for eachparent

    Example 1 Finds the last span in each matched div and adds some css plus a hover state

    Javascript

    $(div spanlast-child) css(colorred fontSize80) hover(function () $(this)addClass(solast) function () $(this)removeClass(solast) )

    CSS

    spansolast text-decorationl ine-through

    HTML

    ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

    ltspangtSamltspangt ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt

    ltspangtRalphltspangt ltspangtDavidltspangt ltdivgt

    first-child $(first-child)

    Selects all elements that are the f irst child of their parent

    Added in version 114

    $(f irst-child)

    While f irst matches only a single element the f irst-child selector can match more than oneone for each parent This is equivalent to nth-child(1)

    Example 1 Finds the f irst span in each matched div to underline and add a hover state

    Javascript

    $(div spanfirst-child) css(text-decoration underline) hover(function () $(this)addClass(sogreen) function () $(this)removeClass(sogreen) )

    CSS

    span color008 spansogreen colorgreen font-weight bolder

    HTML

    ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

    ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt ltspangtRalphltspangt

    ltdivgt

    nth-child $(nth-child(indexevenoddequation))

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

    Added in version 114

    $(nth-child(indexevenoddequat ion))

    indexNumberString The index of each child to match start ing with 1 the string evenor odd or an equat ion ( eg nth-child(even) nth-child(4n) )

    Because jQuerys implementat ion of nth-child(n) is strict ly derived from the CSS specif icat ionthe value of n is 1-indexed meaning that the count ing starts at 1 For all other selectorexpressions however jQuery follows JavaScript s 0-indexed count ing Therefore given asingle ltulgt containing two ltligts $(linth-child(1)) selects the f irst ltligt while $(lieq(1)) selectsthe second

    The nth-child(n) pseudo-class is easily confused with eq(n) even though the two can result indramat ically dif ferent matched elements With nth-child(n) all children are counted regardlessof what they are and the specif ied element is selected only if it matches the selector at tachedto the pseudo-class With eq(n) only the selector at tached to the pseudo-class is counted notlimited 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 W3C CSS specif icat ion

    Example 1 Finds the second li in each matched ul and notes it

    Javascript

    $(ul l i nth-child(2))append(ltspangt - 2ndltspangt)

    CSS

    div floatleft span colorblue

    HTML

    ltdivgtltulgt ltligtJohnltligt ltligtKarlltl igt ltligtBrandonltligt

    ltulgtltdivgt ltdivgtltulgt ltligtSamltligt ltulgtltdivgt

    ltdivgtltulgt ltligtGlenltligt ltligtTaneltligt ltligtRalphltligt

    ltligtDavidltligt ltulgtltdivgt

    Example 2 This is a playground to see how the selector works with dif ferent strings Not icethat this is dif ferent f rom the even and odd which have no regard for parent and just f ilter thelist of elements to every other one The nth-child however counts the index of the child to itspart icular parent In any case it s easier to see than explain so

    Javascript

    $(button)cl ick(function () var str = $(this)text() $(tr)css(background white) $(tr + str)css(background ff0000) $(inner)text(str) )

    CSS

    button displayblock font-size12px width100px div floatleft margin10px font-size10px border1px solid black span colorblue font-size18px inner colorred td width50px text-aligncenter

    HTML

    ltdivgt ltbuttongtnth-child(even)ltbuttongt ltbuttongtnth-child(odd)ltbuttongt ltbuttongtnth-child(3n)ltbuttongt

    ltbuttongtnth-child(2)ltbuttongt ltdivgt ltdivgt ltbuttongtnth-child(3n+1)ltbuttongt ltbuttongtnth-child(3n+2)ltbuttongt

    ltbuttongtevenltbuttongt ltbuttongtoddltbuttongt ltdivgt ltdivgtlttablegt

    lttrgtlttdgtJohnlttdgtlttrgt lttrgtlttdgtKarllttdgtlttrgt lttrgtlttdgtBrandonlttdgtlttrgt

    lttrgtlttdgtBenjaminlttdgtlttrgt lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtSamlttdgtlttrgt

    lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtGlenlttdgtlttrgt lttrgtlttdgtTanelttdgtlttrgt

    lttrgtlttdgtRalphlttdgtlttrgt lttrgtlttdgtDavidlttdgtlttrgt lttrgtlttdgtMikelttdgtlttrgt

    lttrgtlttdgtDanlttdgtlttrgt lttablegtltdivgt ltspangt trltspan id=innergtltspangt

    ltspangt

    attributeContainsPrefix $([attribute|=value])

    Selects elements that have the specif ied at t ribute with a value either equal to a given string orstart ing with that string followed by a hyphen (-)

    Added in version 10

    $([at t ribute|=value])

    attributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    This selector was introduced into the CSS specif icat ion to handle language at t ributes

    Example 1 Finds all links with an href lang at t ribute that is english

    Javascript

    $(a[hreflang|=en])css(border3px dotted green)

    HTML

    lta href=examplehtml hreflang=engtSome textltagt

    lta href=examplehtml hreflang=en-UKgtSome other textltagt

    lta href=examplehtml hreflang=englishgtwill not be outl inedltagt

    CSS

    a display inl ine-block

    attributeContainsWord $([attribute~=value])

    Selects elements that have the specif ied at t ribute with a value containing a given worddelimited by spaces

    Added in version 10

    $([at t ribute~=value])

    at t ributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    This selector matches the test string against each word in the at t ribute value where a word isdef ined as a string delimited by whitespace The selector matches if the test string is exact lyequal to any of the words

    Example 1 Finds all inputs with a name attribute that contains the word man and sets the

    value with some text

    Javascript

    $( input[name~=man])val(mr man is in it)

    HTML

    ltinput name=man-news gt

    ltinput name=milk man gt ltinput name=letterman2 gt ltinput name=newmilk gt

    attributeMultiple$([attributeFilter1][attributeFilter2][attributeFilterN])

    Matches elements that match all of the specif ied at t ribute f ilters

    Added in version 10

    $([at t ributeFilter1][at t ributeFilter2][at t ributeFilterN])

    at t ributeFilter1Selector An at t ribute f ilter

    at t ributeFilter2Selector Another at t ribute f ilter reducing the select ion even more

    attributeFilterNSelector (opt ional) As many more at t ribute f ilters as necessary

    Example 1 Finds all inputs that have an id at t ribute and whose name attribute ends with manand sets the value

    Javascript

    $( input[id][name$=man])val(only this one)

    HTML

    ltinput id=man-news name=man-news gt

    ltinput name=milkman gt ltinput id=letterman name=new-letterman gt ltinput name=newmilk gt

    attributeContains $([attribute=value])

    Selects elements that have the specif ied at t ribute with a value containing the a given substring

    Added in version 10

    $([at t ribute=value])

    at t ributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    This is the most generous of the jQuery at t ribute selectors that match against a value It willselect an element if the selectors string appears anywhere within the element s at t ribute valueCompare this selector with the Attribute Contains Word selector (eg [at t r~=word]) which ismore appropriate in many cases

    Example 1 Finds all inputs with a name attribute that contains man and sets the value withsome text

    Javascript

    $( input[name=man])val(has man in it)

    HTML

    ltinput name=man-news gt

    ltinput name=milkman gt ltinput name=letterman2 gt ltinput name=newmilk gt

    attributeEndsWith $([attribute$=value])

    Selects elements that have the specif ied at t ribute with a value ending exact ly with a givenstring The comparison is case sensit ive

    Added in version 10

    $([at t ribute$=value])

    at t ributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    Example 1 Finds all inputs with an at t ribute name that ends with let ter and puts text in them

    Javascript

    $( input[name$=letter])val(a letter)

    HTML

    ltinput name=newsletter gt

    ltinput name=milkman gt ltinput name=jobletter gt

    attributeStartsWith $([attribute^=value])

    Selects elements that have the specif ied at t ribute with a value beginning exact ly with a givenstring

    Added in version 10

    $([at t ribute^=value])

    at t ributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    This selector can be useful for ident ifying elements in pages produced by server-sideframeworks that produce HTML with systemat ic element IDs However it will be slower thanusing a class selector so leverage classes if you can to group like elements

    Example 1 Finds all inputs with an at t ribute name that starts with news and puts text in them

    Javascript

    $( input[name^=news])val(news here)

    HTML

    ltinput name=newsletter gt

    ltinput name=milkman gt ltinput name=newsboy gt

    attributeNotEqual $([attribute=value])

    Select elements that either dont have the specif ied at t ribute or do have the specif ied at t ributebut not with a certain value

    Added in version 10

    $([at t ribute=value])

    at t ributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    This selector is equivalent to not([at t r=value])

    Example 1 Finds all inputs that dont have the name newslet ter and appends text to the spannext to it

    Javascript

    $( input[name=newsletter])next()append(ltbgt not newsletterltbgt)

    HTML

    ltdivgt

    ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtname is newsletterltspangt

    ltdivgt ltdivgt ltinput type=radio value=Cold Fusion gt ltspangtno nameltspangt

    ltdivgt ltdivgt ltinput type=radio name=accept value=Evil Plans gt

    ltspangtname is acceptltspangt ltdivgt

    attributeEquals $([attribute=value])

    Selects elements that have the specif ied at t ribute with a value exact ly equal to a certain value

    Added in version 10

    $([at t ribute=value])

    attributeString An at t ribute name

    valueString An at t ribute value Quotes are mandatory

    Example 1 Finds all inputs with a value of Hot Fuzz and changes the text of the next siblingspan

    Javascript

    $( input[value=Hot Fuzz])next()text( Hot Fuzz)

    HTML

    ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtnameltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Cold Fusion gt ltspangtvalueltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Evil Plans gt ltspangtvalueltspangt ltlabelgt ltdivgt

    attributeHas $([attribute])

    Selects elements that have the specif ied at t ribute with any value

    Added in version 10

    $([at t ribute])

    at t ributeString An at t ribute name

    Example 1 Bind a single click that adds the div id to its text

    Javascript

    $(div[id])one(cl ick function() var idString = $(this)text() + = + $(this)attr( id) $(this)text(idString) )

    HTML

    ltdivgtno idltdivgt ltdiv id=heygtwith idltdivgt

    ltdiv id=theregthas an idltdivgt ltdivgtnopeltdivgt

    visible $(visible)

    Selects all elements that are visible

    Added in version 10

    $(visible)

    Elements can be considered hidden for several reasons

    They have a CSS display value of none

    They are form elements with type=hidden

    Their width and height are explicit ly set to 0

    An ancestor element is hidden so the element is not shown on the page

    Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start at the animat ion

    How visible is calculated was changed in jQuery 132 The release notes out line the changes inmore detail

    Example 1 Make all visible divs turn yellow on click

    Javascript

    $(divvisible)cl ick(function () $(this)css(background yellow) ) $(button)cl ick(function () $(divhidden)show(fast) )

    CSS

    div width50px height40px margin5px border3px outset green floatleft starthidden displaynone

    HTML

    ltbuttongtShow hidden to see they dont changeltbuttongt ltdivgtltdivgt ltdiv class=starthiddengtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdiv style=displaynonegtltdivgt

    hidden $(hidden)

    Selects all elements that are hidden

    Added in version 10

    $(hidden)

    Elements can be considered hidden for several reasons

    They have a CSS display value of none

    They are form elements with type=hidden

    Their width and height are explicit ly set to 0

    An ancestor element is hidden so the element is not shown on the page

    Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start of the animat ion

    How hidden is determined was changed in jQuery 132 An element is assumed to be hidden if itor any of its parents consumes no space in the document CSS visibility isnt taken into account(therefore $(elem)css(visibilityhidden)is(hidden) == false) The release notes out line thechanges in more detail

    Example 1 Shows all hidden divs and counts hidden inputs

    Javascript

    in some browsers hidden includes head title script etcvar hiddenEls = $(body)find(hidden)not(script)

    $(spanfirst)text(Found + hiddenElslength + hidden elements total)$(divhidden)show(3000)$(spanlast)text(Found + $(inputhidden)length + hidden inputs)

    CSS

    div width70px height40px backgroundee77ff margin5px floatleft span displayblock clearleft colorred starthidden displaynone

    HTML

    ltspangtltspangt ltdivgtltdivgt ltdiv style=displaynonegtHiderltdivgt ltdivgtltdivgt

    ltdiv class=starthiddengtHiderltdivgt ltdivgtltdivgt ltformgt ltinput type=hidden gt

    ltinput type=hidden gt ltinput type=hidden gt ltformgt ltspangt

    ltspangt

    parent $(parent)

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

    Added in version 10

    $(parent)

    This is the inverse of empty

    One important thing to note regarding the use of parent (and empty) is that child elementsinclude text nodes

    The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elements

    on the other hand are empty (ie have no children) by def init ion ltinputgt ltimggt ltbrgt and lthrgtfor example

    Example 1 Finds all tds with children including text

    Javascript

    $(tdparent)fadeTo(1500 03)

    CSS

    td width40px backgroundgreen

    HTML

    lttable border=1gt

    lttrgtlttdgtValue 1lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtValue 2lttdgtlttdgtlttdgtlttrgt

    lttablegt

    has $(has(selector))

    Selects elements which contain at least one element that matches the specif ied selector

    Added in version 114

    $(has(selector))

    selectorSelector Any selector

    The expression $(divhas(p)) matches a ltdivgt if a ltpgt exists anywhere among its descendantsnot just as a direct child

    Example 1 Adds the class test to all divs that have a paragraph inside of them

    Javascript

    $(divhas(p))addClass(test)

    HTML

    ltdivgtltpgtHello in a paragraphltpgtltdivgt

    ltdivgtHello again (with no paragraph)ltdivgt

    CSS

    test border 3px inset red

    empty $(empty)

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

    Added in version 10

    $(empty)

    This is the inverse of parent

    One important thing to note with empty (and parent) is that child elements include text nodes

    The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elementson the other hand are empty (ie have no children) by def init ion and

    for example

    Example 1 Finds all elements that are empty - they dont have child elements or text

    Javascript

    $(tdempty)text(Was empty)css(background rgb(255220200))

    CSS

    td text-aligncenter

    HTML

    lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtTD 2lttdgtlttdgtlttdgtlttrgt

    lttrgtlttdgtlttdgtlttdgtTD5lttdgtlttrgt lttablegt

    contains $(contains(text))

    Select all elements that contain the specif ied text

    Added in version 114

    $(contains(text))

    text String A string of text to look for It s case sensit ive

    The matching text can appear direct ly within the selected element in any of that element sdescendants or a combinat ion thereof As with at t ribute value selectors text inside theparentheses of contains() can be writ ten as bare words or surrounded by quotat ion marks Thetext must have matching case to be selected

    Example 1 Finds all divs containing John and underlines them

    Javascript

    $(divcontains( John))css(text-decoration underline)

    HTML

    ltdivgtJohn Resigltdivgt

    ltdivgtGeorge MartinltdivgtltdivgtMalcom John SinclairltdivgtltdivgtJ Ohnltdivgt

    animated $(animated)

    Select all elements that are in the progress of an animat ion at the t ime the selector is run

    Added in version 12

    $(animated)

    Example 1 Change the color of any div that is animated

    Javascript

    $(run)cl ick(function() $(divanimated)toggleClass(colored) ) function animateIt() $(mover)sl ideToggle(slow animateIt) animateIt()

    HTML

    ltbutton id=rungtRunltbuttongt

    ltdivgtltdivgt ltdiv id=movergtltdivgt ltdivgtltdivgt

    CSS

    div backgroundyellow border1px solid AAA width80px height80px margin0 5px floatleft divcolored backgroundgreen

    header $(header)

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

    Added in version 12

    $(header)

    Example 1 Adds a background and text color to all the headers on the page

    Javascript

    $(header)css( backgroundCCC colorblue )

    HTML

    lth1gtHeader 1lth1gt

    ltpgtContents 1ltpgt lth2gtHeader 2lth2gt ltpgtContents 2ltpgt

    CSS

    body font-size 10px font-family Arial h1 h2 margin 3px 0

    lt $(lt(index))

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

    Added in version 10

    $(lt (index))

    indexNumber Zero-based index

    index-related selectors

    The index-related selectors (including this less than selector) f ilter the set of elements thathave matched the expressions that precede them They narrow the set down based on theorder of the elements within this matched set For example if elements are f irst selected with aclass selector (myclass) and four elements are returned these elements are given indices 0through 3 for the purposes of these selectors

    Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasslt (1)) selects the f irst element in the document with the class myclass ratherthan select ing no elements In contrast nth-child(n) uses 1-based indexing to conform to theCSS specif icat ion

    Example 1 Finds TDs less than the one with the 4th index (TD4)

    Javascript

    $(tdlt(4))css(color red)

    HTML

    lttable border=1gt

    lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

    lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

    gt $(gt(index))

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

    Added in version 10

    $(gt(index))

    indexNumber Zero-based index

    index-related selectors

    The index-related selector expressions (including this greater than selector) f ilter the set ofelements that have matched the expressions that precede them They narrow the set downbased on the order of the elements within this matched set For example if elements are f irstselected with a class selector (myclass) and four elements are returned these elements aregiven indices 0 through 3 for the purposes of these selectors

    Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclassgt(1)) selects elements af ter the second element in the document with theclass myclass rather than af ter the f irst In contrast nth-child(n) uses 1-based indexing toconform to the CSS specif icat ion

    Example 1 Finds TD 5 and higher Reminder the indexing starts at 0

    Javascript

    $(tdgt(4))css(text-decoration l ine-through)

    HTML

    lttable border=1gt

    lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

    lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgt lttablegt

    eq $(eq(index))

    Select the element at index n within the matched set

    Added in version 10

    $(eq(index))

    indexNumber Zero-based index of the element to match

    The index-related selectors (eq() lt () gt() even odd) f ilter the set of elements that havematched the expressions that precede them They narrow the set down based on the order ofthe elements within this matched set For example if elements are f irst selected with a classselector (myclass) and four elements are returned these elements are given indices 0 through3 for the purposes of these selectors

    Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasseq(1)) selects the second element in the document with the class myclassrather than the f irst In contrast nth-child(n) uses 1-based indexing to conform to the CSSspecif icat ion

    Unlike the eq(index) method the eq(index) selector does not accept a negat ive value for indexFor example while $(li)eq(-1) selects the last li element $(lieq(-1)) selects nothing

    Example 1 Finds the third td

    Javascript

    $(tdeq(2))css(color red)

    HTML

    lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

    Example 2 Apply three dif ferent styles to list items to demonstrate that eq() is designed toselect a single element while nth-child() or eq() within a looping construct such as each() canselect mult iple elements

    Javascript

    applies yellow background color to a single ltligt$(ulnav l i eq(1))css( backgroundColor ff0 )

    applies ital ics to text of the second ltligt within each ltul class=navgt$(ulnav)each(function(index) $(this)find(l i eq(1))css( fontStyle ital ic ))

    applies red text color to descendants of ltul class=navgt for each ltligt that is the second child of its parent$(ulnav l i nth-child(2))css( color red )

    HTML

    ltul class=navgt ltligtList 1 item 1ltligt ltligtList 1 item 2ltligt ltligtList 1 item 3ltligtltulgtltul class=navgt ltligtList 2 item 1ltligt ltligtList 2 item 2ltligt ltligtList 2 item 3ltligtltulgt

    odd $(odd)

    Selects odd elements zero-indexed See also even

    Added in version 10

    $(odd)

    In part icular note that the 0-based indexing means that counter-intuit ively odd selects thesecond element fourth element and so on within the matched set

    Example 1 Finds odd table rows matching the second fourth and so on (index 1 3 5 etc)

    Javascript

    $(trodd)css(background-color bbbbff)

    CSS

    table backgroundf3f7f5

    HTML

    lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

    lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

    even $(even)

    Selects even elements zero-indexed See also odd

    Added in version 10

    $(even)

    In part icular note that the 0-based indexing means that counter-intuit ively even selects thef irst element third element and so on within the matched set

    Example 1 Finds even table rows matching the f irst third and so on (index 0 2 4 etc)

    Javascript

    $(treven)css(background-color bbbbff)

    CSS

    table backgroundeeeeee

    HTML

    lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

    lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

    not $(not(selector))

    Selects all elements that do not match the given selector

    Added in version 10

    $(not(selector))

    selectorSelector A selector with which to f ilter by

    All selectors are accepted inside not() for example not(div a) and not(diva)

    Additional Notes

    The not() method will end up providing you with more readable select ions than pushingcomplex selectors or variables into a not() selector f ilter In most cases it is a better choice

    Example 1 Finds all inputs that are not checked and highlights the next sibling span Not icethere is no change when clicking the checkboxes since no click events have been linked

    Javascript

    $(inputnot(checked) + span)css(background-color yellow) $(input)attr(disabled disabled)

    HTML

    ltdivgt ltinput type=checkbox name=a gt ltspangtMaryltspangtltdivgt

    ltdivgt ltinput type=checkbox name=b gt ltspangtlcmltspangt

    ltdivgtltdivgt ltinput type=checkbox name=c checked=checked gt

    ltspangtPeterltspangtltdivgt

    last $(last)

    Selects the last matched element

    Added in version 10

    $(last)

    Note that last selects a single element by f iltering the current jQuery collect ion and matchingthe last element within it

    Example 1 Finds the last table row

    Javascript

    $(trlast)css(backgroundColor yellow fontWeight bolder)

    HTML

    lttablegt

    lttrgtlttdgtFirst Rowlttdgtlttrgt lttrgtlttdgtMiddle Rowlttdgtlttrgt lttrgtlttdgtLast Rowlttdgtlttrgt

    lttablegt

    first $(first)

    Selects the f irst matched element

    Added in version 10

    $(f irst)

    The f irst pseudo-class is equivalent to eq(0) It could also be writ ten as lt (1) While thismatches only a single element f irst-child can match more than one One for each parent

    Example 1 Finds the f irst table row

    Javascript

    $(trfirst)css(font-style ital ic)

    CSS

    td colorblue font-weightbold

    HTML

    lttablegt lttrgtlttdgtRow 1lttdgtlttrgt lttrgtlttdgtRow 2lttdgtlttrgt

    lttrgtlttdgtRow 3lttdgtlttrgt lttablegt

    next siblings $(prev ~ siblings)

    Selects all sibling elements that follow af ter the prev element have the same parent andmatch the f iltering siblings selector

    Added in version 10

    $(prev ~ siblings)

    prevSelector Any valid selector

    siblingsSelector A selector to f ilter elements that are the following siblings of the f irstselector

    The notable dif ference between (prev + next) and (prev ~ siblings) is their respect ive reachWhile the former reaches only to the immediately following sibling element the lat ter extendsthat reach to all following sibling elements

    Example 1 Finds all divs that are siblings af ter the element with prev as its id Not ice the spanisnt selected since it is not a div and the niece isnt selected since it is a child of a sibling notan actual sibling

    Javascript

    $(prev ~ div)css(border 3px groove blue)

    CSS

    divspan displayblock width80px height80px margin5px backgroundbbffaa floatleft font-size14px divsmall width60px height25px font-size12px backgroundfab

    HTML

    ltdivgtdiv (doesnt match since before prev)ltdivgt ltspan id=prevgtspanprevltspangt ltdivgtdiv siblingltdivgt

    ltdivgtdiv sibling ltdiv id=smallgtdiv nieceltdivgtltdivgt ltspangtspan sibling (not div)ltspangt ltdivgtdiv siblingltdivgt

    next adjacent $(prev + next)

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

    Added in version 10

    $(prev + next)

    prevSelector Any valid selector

    nextSelector A selector to match the element that is next to the f irst selector

    One important point to consider with both the next adjacent sibling selector (prev + next) andthe general sibling selector (prev ~ siblings) is that the elements on either side of thecombinator must share the same parent

    Example 1 Finds all inputs that are next to a label

    Javascript

    $(label + input)css(color blue)val(Labeled)

    HTML

    ltformgt

    ltlabelgtNameltlabelgt ltinput name=name gt ltfieldsetgt ltlabelgtNewsletterltlabelgt

    ltinput name=newsletter gt ltfieldsetgt ltformgt ltinput name=none gt

    child $(parent gt child)

    Selects all direct child elements specif ied by child of elements specif ied by parent

    Added in version 10

    $(parent gt child)

    parentSelector Any valid selector

    childSelector A selector to f ilter the child elements

    As a CSS selector the child combinator is supported by all modern web browsers includingSafari Firefox Opera Chrome and Internet Explorer 7 and above but notably not by InternetExplorer versions 6 and below However in jQuery this selector (along with all others) worksacross all supported browsers including IE6

    The child combinator (E gt F) can be thought of as a more specif ic form of the descendantcombinator (E F) in that it selects only f irst-level descendants

    Note The $(gt elem context) selector will be deprecated in a future release Itsusage is thus discouraged in lieu of using alternative selectors

    Example 1 Places a border around all list items that are children of

    Javascript

    $(ultopnav gt l i)css(border 3px double red)

    CSS

    body font-size14px

    HTML

    ltul class=topnavgt ltligtItem 1ltligt ltligtItem 2 ltulgtltligtNested item 1ltligtltligtNested item 2ltligtltligtNested item 3ltligtltulgt ltl igt ltligtItem 3ltligtltulgt

    descendant $(ancestor descendant)

    Selects all elements that are descendants of a given ancestor

    Added in version 10

    $(ancestor descendant)

    ancestorSelector Any valid selector

    descendantSelector A selector to f ilter the descendant elements

    A descendant of an element could be a child grandchild great-grandchild and so on of thatelement

    Example 1 Finds all input descendants of forms

    Javascript

    $(form input)css(border 2px dotted blue)

    CSS

    body font-size14px form border2px green solid padding2px margin0 backgroundefe div colorred fieldset margin1px padding3px

    HTML

    ltformgt ltdivgtForm is surrounded by the green outl ineltdivgt ltlabelgtChildltlabelgt ltinput name=name gt

    ltfieldsetgt ltlabelgtGrandchildltlabelgt ltinput name=newsletter gt ltfieldsetgt

    ltformgt Sibling to form ltinput name=none gt

    multiple $(selector1 selector2 selectorN)

    Selects the combined results of all the specif ied selectors

    Added in version 10

    $(selector1 selector2 selectorN)

    selector1Selector Any valid selector

    selector2Selector Another valid selector

    selectorNSelector (opt ional) As many more valid selectors as you like

    You can specify any number of selectors to combine into a single result This mult ipleexpression combinator is an ef f icient way to select disparate elements The order of the DOMelements in the returned jQuery object may not be ident ical as they will be in document orderAn alternat ive to this combinator is the add() method

    Example 1 Finds the elements that match any of these three selectors

    Javascript

    $(divspanpmyClass)css(border3px solid red)

    HTML

    ltdivgtdivltdivgt

    ltp class=myClassgtp class=myClassltpgt ltp class=notMyClassgtp class=notMyClassltpgt ltspangtspanltspangt

    CSS

    divspanp width 126px height 60px floatleft padding 3px margin 2px background-color EEEEEE font-size14px

    Example 2 Show the order in the jQuery object

    Javascript

    var l ist = $(divpspan)map(function () return thistagName )get()join( ) $(b)append(documentcreateTextNode(list))

    CSS

    b colorred font-size16px displayblock clearleft divspanp width 40px height 40px floatleft margin 10px background-color blue padding3px colorwhite

    HTML

    ltspangtspanltspangt

    ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt ltspangtspanltspangt

    ltpgtpltpgt ltdivgtdivltdivgt ltbgtltbgt

    all $()

    Selects all elements

    Added in version 10

    $()

    Caut ion The all or universal selector is extremely slow except when used by itself

    Example 1 Finds every element (including head body etc) in the document

    Javascript

    var elementCount = $()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

    HTML

    ltdivgtDIVltdivgt

    ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgt

    CSS

    h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE

    Example 2 A common way to select all elements is to f ind within documentbody so elementslike head script etc are lef t out

    Javascript

    var elementCount = $(test)find()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

    HTML

    ltdiv id=testgt ltdivgtDIVltdivgt ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgtltdivgt

    CSS

    h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE test width auto height auto background-color transparent

    class $(class)

    Selects all elements with the given class

    Added in version 10

    $(class)

    classString A class to search for An element can have mult iple classes only one ofthem must match

    For class selectors jQuery uses JavaScript s nat ive getElementsByClassName() funct ion if thebrowser supports it

    Example 1 Finds the element with the class myClass

    Javascript

    $(myClass)css(border3px solid red)

    HTML

    ltdiv class=notMegtdiv class=notMeltdivgt

    ltdiv class=myClassgtdiv class=myClassltdivgt ltspan class=myClassgtspan class=myClassltspangt

    CSS

    divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

    Example 2 Finds the element with both myclass and otherclass classes

    Javascript

    $(myclassotherclass)css(border13px solid red)

    HTML

    ltdiv class=myclassgtdiv class=notMeltdivgt

    ltdiv class=myclass otherclassgtdiv class=myClassltdivgt ltspan class=myclass otherclassgtspan class=myClassltspangt

    CSS

    divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

    element $(element)

    Selects all elements with the given tag name

    Added in version 10

    $(element)

    elementString An element to search for Refers to the tagName of DOM nodes

    JavaScript s getElementsByTagName() funct ion is called to return the appropriate elementswhen this expression is used

    Example 1 Finds every DIV element

    Javascript

    $(div)css(border9px solid red)

    HTML

    ltdivgtDIV1ltdivgt

    ltdivgtDIV2ltdivgt ltspangtSPANltspangt

    CSS

    divspan width 60px height 60px floatleft padding 10px margin 10px background-color EEEEEE

    id $(id)

    Selects a single element with the given id at t ribute

    Added in version 10

    $( id)

    idString An ID to search for specif ied via the id at t ribute of an element

    For id selectors jQuery uses the JavaScript funct ion documentgetElementById() which isextremely ef f icient When another selector is at tached to the id selector such as h2pageTit lejQuery performs an addit ional check before ident ifying the element as a match

    As always remember that as a developer your time is typically the most valuableresource Do not focus on optimization of selector speed unless it is clear thatperformance needs to be improved

    Each id value must be used only once within a document If more than one element has beenassigned the same ID queries that use that ID will only select the f irst matched element in theDOM This behavior should not be relied on however a document with more than one elementusing the same ID is invalid

    If the id contains characters like periods or colons you have to escape those characters withbackslashes

    Example 1 Finds the element with the id myDiv

    Javascript

    $(myDiv)css(border3px solid red)

    HTML

    ltdiv id=notMegtltpgtid=notMeltpgtltdivgt

    ltdiv id=myDivgtid=myDivltdivgt

    CSS

    div width 90px height 90px floatleft padding 5px margin 5px background-color EEEEEE

    Example 2 Finds the element with the id myIDentry[1] See how certain characters must beescaped with backslashes

    Javascript

    $(myIDentry[1])css(border3px solid red)

    HTML

    ltdiv id=myIDentry[0]gtid=myIDentry[0]ltdivgt

    ltdiv id=myIDentry[1]gtid=myIDentry[1]ltdivgt ltdiv id=myIDentry[2]gtid=myIDentry[2]ltdivgt

    CSS

    div width 300px floatleft padding 2px margin 3px background-color EEEEEE

    Traversing

    has

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

    Added in version 14

    has(contained)jQuery

    containedElement A DOM element to match elements against

    Given a jQuery object that represents a set of DOM elements the has() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst the descendants of the matching elements the element will be included in the result ifany of its descendant elements matches the selector

    Consider a page with a nested list as follows

    ltulgt ltligtlist item 1ltligt ltligtlist item 2 ltulgt ltligtlist item 2-altligt ltligtlist item 2-bltligt ltulgt ltl igt ltligtlist item 3ltligt ltligtlist item 4ltligtltulgt

    We can apply this method to the set of list items as follows

    $( l i )has(ul )css(background-color red)

    The result of this call is a red background for item 2 as it is the only ltligt that has a ltulgt amongits descendants

    Example 1 Check if an element is inside another

    Javascript

    $(ul)append(ltligt + ($(ul)has(l i)length Yes No) + ltl igt) $(ul)has(l i)addClass(full)

    CSS

    ful l border 1px solid red

    HTML

    ltulgtltligtDoes the UL contain an LIltl igtltulgt

    parentsUntil

    Get the ancestors of each element in the current set of matched elements up to but notincluding the element matched by the selector DOM node or jQuery object

    Added in version 16

    parentsUnt il(element f ilter)jQuery

    elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching ancestor elements

    f ilterSelector (opt ional) A string containing a selector expression to matchelements against

    Given a selector expression that represents a set of DOM elements the parentsUnt il() methodtraverses through the ancestors of these elements unt il it reaches an element matched by theselector passed in the methods argument The result ing jQuery object contains all of theancestors up to but not including the one matched by the parentsUnt il() selector

    If the selector is not matched or is not supplied all ancestors will be selected in these cases itselects the same elements as the parents() method does when no selector is provided

    As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstparentsUnt il() argument

    The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

    Example 1 Find the ancestors of

    up to

    and give them a red background color Also f ind ancestors of

    that have a class of yes up toand give them a green border

    Javascript

    $(l i item-a)parentsUntil(level-1) css(background-color red)

    $(l i item-2)parentsUntil( $(ullevel-1) yes ) css(border 3px solid green)

    HTML

    ltul class=level-1 yesgt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2 yesgt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    prevUntil

    Get all preceding siblings of each element up to but not including the element matched by theselector DOM node or jQuery object

    Added in version 16

    prevUnt il(element f ilter)jQuery

    elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching preceding sibling elements

    f ilterSelector (opt ional) A string containing a selector expression to matchelements against

    Given a selector expression that represents a set of DOM elements the prevUnt il() methodsearches through the predecessors of these elements in the DOM tree stopping when itreaches an element matched by the methods argument The new jQuery object that isreturned contains all previous siblings up to but not including the one matched by theprevUnt il() selector the elements are returned in order f rom the closest sibling to the farthest

    If the selector is not matched or is not supplied all previous siblings will be selected in thesecases it selects the same elements as the prevAll() method does when no f ilter selector isprovided

    As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstprevUnt il() argument

    The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

    Example 1 Find the siblings that precede

    up to the precedingand give them a red background color Also f ind previous

    siblings ofup toand give them a green text color

    Javascript

    $(term-2)prevUntil(dt) css(background-color red) var term1 = documentgetElementById(term-1)$(term-3)prevUntil(term1 dd) css(color green)

    HTML

    ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

    ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

    ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

    nextUntil

    Get all following siblings of each element up to but not including the element matched by theselector DOM node or jQuery object passed

    Added in version 16

    nextUnt il(element f ilter)jQuery

    elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching following sibling elements

    f ilterSelector (opt ional) A string containing a selector expression to matchelements against

    Given a selector expression that represents a set of DOM elements the nextUnt il() methodsearches through the successors of these elements in the DOM tree stopping when it reachesan element matched by the methods argument The new jQuery object that is returnedcontains all following siblings up to but not including the one matched by the nextUnt il()argument

    If the selector is not matched or is not supplied all following siblings will be selected in thesecases it selects the same elements as the nextAll() method does when no f ilter selector isprovided

    As of jQuery 16 A DOM node or jQuery object instead of a selector may be passed to thenextUnt il() method

    The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

    Example 1 Find the siblings that follow

    up to the nextand give them a red background color Also f ind

    siblings that followup toand give them a green text color

    Javascript

    $(term-2)nextUntil(dt) css(background-color red)

    var term3 = documentgetElementById(term-3)$(term-1)nextUntil(term3 dd) css(color green)

    HTML

    ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

    ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

    ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

    each

    Iterate over a jQuery object execut ing a funct ion for each matched element

    Added in version 10

    each(funct ion(index Element))jQuery

    funct ion(index Element)Funct ion A funct ion to execute for each matched element

    The each() method is designed to make DOM looping constructs concise and less error-proneWhen called it iterates over the DOM elements that are part of the jQuery object Each t ime thecallback runs it is passed the current loop iterat ion beginning from 0 More important ly thecallback is f ired in the context of the current DOM element so the keyword this refers to theelement

    Suppose we had a simple unordered list on the page

    ltulgt ltligtfooltligt ltligtbarltligt ltulgt

    We can select the list items and iterate across them

    $( l i )each(function(index) alert(index + + $(this)text()) )

    A message is thus alerted for each item in the list

    0 foo

    1 bar

    We can stop the loop from within the callback funct ion by returning false

    Example 1 Iterates over three divs and sets their color property

    Javascript

    $(documentbody)cl ick(function () $(div)each(function (i) i f (thisstylecolor = blue) thisstylecolor = blue else thisstylecolor = ) )

    CSS

    div colorred text-aligncenter cursorpointer font-weightbolder width300px

    HTML

    ltdivgtClick hereltdivgt

    ltdivgtto iterate throughltdivgt ltdivgtthese divsltdivgt

    Example 2 If you want to have the jQuery object instead of the regular DOM element use the$(this) funct ion for example

    Javascript

    $(span)cl ick(function () $(l i)each(function() $(this)toggleClass(example) ) )

    CSS

    ul font-size18px margin0 span colorblue text-decorationunderline cursorpointer example font-styleital ic

    HTML

    To do l ist ltspangt(click here to change)ltspangt ltulgt ltligtEatltligt ltligtSleepltligt

    ltligtBe merryltligt ltulgt

    Example 3 You can use return to break out of each() loops early

    Javascript

    $(button)cl ick(function () $(div)each(function (index domEle) domEle == this $(domEle)css(backgroundColor yellow) i f ($(this)is(stop)) $(span)text(Stopped at div index + index) return false ) )

    CSS

    div width40px height40px margin5px floatleft border2px blue solid text-aligncenter span colorred

    HTML

    ltbuttongtChange colorsltbuttongt ltspangtltspangt ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdiv id=stopgtStop hereltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt

    first

    Reduce the set of matched elements to the f irst in the set

    Added in version 14

    f irst()jQuery

    [

    Given a jQuery object that represents a set of DOM elements the f irst() method constructs anew jQuery object f rom the f irst matching element

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    We can apply this method to the set of list items

    $( l i )first()css(background-color red)

    The result of this call is a red background for the f irst item

    Example 1 Highlight the f irst span in a paragraph

    CSS

    highlightbackground-color yellow

    Javascript

    $(p span)first()addClass(highlight)

    HTML

    ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

    last

    Reduce the set of matched elements to the f inal one in the set

    Added in version 14

    last()jQuery

    [

    Given a jQuery object that represents a set of DOM elements the last() method constructs anew jQuery object f rom the last matching element

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    We can apply this method to the set of list items

    $( l i )last()css(background-color red)

    The result of this call is a red background for the f inal item

    Example 1 Highlight the last span in a paragraph

    CSS

    highlightbackground-color yellow

    Javascript

    $(p span)last()addClass(highlight)

    HTML

    ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

    slice

    Reduce the set of matched elements to a subset specif ied by a range of indices

    Added in version 114

    slice(start end)jQuery

    start Integer An integer indicat ing the 0-based posit ion at which the elements begin tobe selected If negat ive it indicates an of fset f rom the end of the set

    endInteger (opt ional) An integer indicat ing the 0-based posit ion at which theelements stop being selected If negat ive it indicates an of fset f rom theend of the set If omit ted the range cont inues unt il the end of the set

    Given a jQuery object that represents a set of DOM elements the slice() method constructs anew jQuery object f rom a subset of the matching elements The supplied start index ident if iesthe posit ion of one of the elements in the set if end is omit ted all elements af ter this one willbe included in the result

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    We can apply this method to the set of list items

    $( l i )sl ice(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 iszero-based and refers to the posit ion of elements within the jQuery object not within theDOM tree

    The end parameter allows us to limit the selected range even further For example

    $( l i )sl ice(2 4)css(background-color red)

    Now only items 3 and 4 are selected The index is once again zero-based the range extends upto but not including the specif ied index

    Negative Indices

    The jQuery slice() method is patterned af ter the JavaScript slice() method for arrays One ofthe features that it mimics is the ability for negat ive numbers to be passed as either the start orend parameter If a negat ive number is provided this indicates a posit ion start ing f rom the endof the set rather than the beginning For example

    $( l i )sl ice(-2 -1)css(background-color red)

    This t ime only list item 4 is turned red since it is the only item in the range between two fromthe end (-2) and one from the end (-1)

    Example 1 Turns divs yellow based on a random slice

    Javascript

    function colorEm() var $div = $(div) var start = Mathfloor(Mathrandom() $divlength) var end = Mathfloor(Mathrandom() ($divlength - start)) + start + 1 i f (end == $divlength) end = undefined $divcss(background ) i f (end) $divsl ice(start end)css(background yellow) else $divsl ice(start)css(background yellow) $(span)text($(div)sl ice( + start + (end + end ) + )css(background yellow))

    $(button)cl ick(colorEm)

    CSS

    div width40px height40px margin10px floatleft border2px solid blue span colorred font-weightbold button margin5px

    HTML

    ltpgtltbuttongtTurn sl ice yellowltbuttongt ltspangtClick the buttonltspangtltpgt ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt

    Example 2 Selects all paragraphs then slices the select ion to include only the f irst element

    Javascript

    $(p)sl ice(0 1)wrapInner(ltbgtltbgt)

    Example 3 Selects all paragraphs then slices the select ion to include only the f irst and secondelement

    Javascript

    $(p)sl ice(0 2)wrapInner(ltbgtltbgt)

    Example 4 Selects all paragraphs then slices the select ion to include only the second element

    Javascript

    $(p)sl ice(1 2)wrapInner(ltbgtltbgt)

    Example 5 Selects all paragraphs then slices the select ion to include only the second and thirdelement

    Javascript

    $(p)sl ice(1)wrapInner(ltbgtltbgt)

    Example 6 Selects all paragraphs then slices the select ion to include only the third element

    Javascript

    $(p)sl ice(-1)wrapInner(ltbgtltbgt)

    end

    End the most recent f iltering operat ion in the current chain and return the set of matchedelements to its previous state

    Added in version 10

    end()jQuery

    Most of jQuerys DOM traversal methods operate on a jQuery object instance and produce anew one matching a dif ferent set of DOM elements When this happens it is as if the new setof elements is pushed onto a stack that is maintained inside the object Each successivef iltering method pushes a new element set onto the stack If we need an older element set wecan use end() to pop the sets back of f of the stack

    Suppose we have a couple short lists on a page

    ltul class=firstgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgtltul class=secondgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgt

    The end() method is useful primarily when exploit ing jQuerys chaining propert ies When notusing chaining we can usually just call up a previous object by variable name so we dont needto manipulate the stack With end() though we can string all the method calls together

    $(ulfirst)find(foo)css(background-color red) end()find(bar)css(background-color green)

    This chain searches for items with the class foo within the f irst list only and turns theirbackgrounds red Then end() returns the object to its state before the call to f ind() so thesecond f ind() looks for bar inside ltul class=f irstgt not just inside that list s ltli class=foogtand turns the matching elements backgrounds green The net result is that items 1 and 3 ofthe f irst 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 f iltering methodsproviding the openings of nested blocks and end() methods closing them

    $(ulfirst)find(foo) css(background-color red)end()find(bar) css(background-color green)end()

    The last end() is unnecessary as we are discarding the jQuery object immediately thereafterHowever when the code is writ ten in this form the end() provides visual symmetry and a senseof complet ion acirceurordquomaking the program at least to the eyes of some developers more readableat the cost of a slight hit to performance as it is an addit ional funct ion call

    Example 1 Selects all paragraphs f inds span elements inside these and reverts the select ionback to the paragraphs

    Javascript

    jQueryfnshowTags = function (n) var tags = thismap(function () return thistagName ) get()join( ) $(beq( + n + ))text(tags) return this

    $(p)showTags(0) find(span) showTags(1) css(background yellow) end() showTags(2) css(font-style ital ic)

    CSS

    p div margin1px padding1px font-weightbold font-size16px div colorblue b colorred

    HTML

    ltpgt Hi there ltspangthowltspangt are you ltspangtdoingltspangt ltpgt

    ltpgt This ltspangtspanltspangt is one of several ltspangtspansltspangt in this ltspangtsentenceltspangt ltpgt

    ltdivgt Tags in jQuery object initial ly ltbgtltbgt ltdivgt ltdivgt Tags in jQuery object after find ltbgtltbgt

    ltdivgt ltdivgt Tags in jQuery object after end ltbgtltbgt ltdivgt

    Example 2 Selects all paragraphs f inds span elements inside these and reverts the select ion

    back to the paragraphs

    Javascript

    $(p)find(span)end()css(border 2px red solid)

    CSS

    p margin10px padding10px

    HTML

    ltpgtltspangtHelloltspangt how are youltpgt

    andSelf

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

    Added in version 12

    andSelf()jQuery

    As described in the discussion for end() jQuery objects maintain an internal stack that keepstrack of changes to the matched set of elements When one of the DOM traversal methods iscalled the new set of elements is pushed onto the stack If the previous set of elements isdesired as well andSelf() can help

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    The result of the following code is a red background behind items 3 4 and 5

    $( l i third-item)nextAll()andSelf() css(background-color red)

    First the init ial selector locates item 3 init ializing the stack with the set containing just this itemThe call to nextAll() then pushes the set of items 4 and 5 onto the stack Finally the andSelf()invocat ion merges these two sets together creat ing a jQuery object that points to all three

    items in document order [ltlithird-itemgtltligtltligt ]

    Example 1 Find all divs and all the paragraphs inside of them and give them both class namesNot ice the div doesnt have the yellow background color since it didnt use andSelf()

    Javascript

    $(div)find(p)andSelf()addClass(border) $(div)find(p)addClass(background)

    CSS

    p div margin5px padding5px border border 2px solid red background backgroundyellow

    HTML

    ltdivgt ltpgtFirst Paragraphltpgt ltpgtSecond Paragraphltpgt ltdivgt

    siblings

    Get the siblings of each element in the set of matched elements opt ionally f iltered by aselector

    Added in version 10

    siblings(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the siblings() method allows usto search through the siblings of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    If we begin at the third item we can f ind its siblings

    $( l i 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 aselector expression all of the siblings are part of the object If we had supplied one only thematching items among these four would be included

    The original element is not included among the siblings which is important to remember whenwe wish to f ind all elements at a part icular level of the DOM tree

    Example 1 Find the unique siblings of all yellow li elements in the 3 lists (including other yellow lielements if appropriate)

    Javascript

    var len = $(hil ite)siblings() css(color red) length $(b)text(len)

    CSS

    ul floatleft margin5px font-size16px font-weightbold p colorblue margin10px 20px font-size16px padding5px font-weightbolder hi l ite backgroundyellow

    HTML

    ltulgt ltligtOneltligt

    ltligtTwoltligt ltli class=hil itegtThreeltligt ltligtFourltligt ltulgt

    ltulgt ltligtFiveltligt ltligtSixltligt ltligtSevenltligt

    ltulgt ltulgt ltligtEightltligt ltli class=hil itegtNineltligt

    ltligtTenltligt ltli class=hil itegtElevenltligt ltulgt ltpgtUnique siblings ltbgtltbgtltpgt

    Example 2 Find all siblings with a class selected of each div

    Javascript

    $(p)siblings(selected)css(background yellow)

    HTML

    ltdivgtltspangtHelloltspangtltdivgt

    ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

    prevAll

    Get all preceding siblings of each element in the set of matched elements opt ionally f iltered bya selector

    Added in version 12

    prevAll(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the prevAll() method searchesthrough the predecessors of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements the elements are returned in order beginning with theclosest sibling

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    If we begin at the third item we can f ind the elements which come before it

    $( l i 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 aselector 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

    Example 1 Locate all the divs preceding the last div and give them a class

    Javascript

    $(divlast)prevAll()addClass(before)

    CSS

    div width70px height70px backgroundabc border2px solid black margin10px floatleft divbefore border-color red

    HTML

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    prev

    Get the immediately preceding sibling of each element in the set of matched elementsopt ionally f iltered by a selector

    Added in version 10

    prev(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the prev() method allows us tosearch through the predecessors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    If we begin at the third item we can f ind the element which comes just before it

    $( l i 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 selectorexpression this preceding element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

    Example 1 Find the very previous sibling of each div

    Javascript

    var $curr = $(start) $currcss(background f99) $(button)cl ick(function () $curr = $currprev() $(div)css(background ) $currcss(background f99) )

    CSS

    div width40px height40px margin10px floatleft border2px blue solid padding2px span font-size14px p clearleft margin10px

    HTML

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltspangthas childltspangtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdiv id=startgtltdivgt

    ltdivgtltdivgt ltpgtltbuttongtGo to Prevltbuttongtltpgt

    Example 2 For each paragraph f ind the very previous sibling that has a class selected

    Javascript

    $(p)prev(selected)css(background yellow)

    HTML

    ltdivgtltspangtHelloltspangtltdivgt

    ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

    parents

    Get the ancestors of each element in the current set of matched elements opt ionally f iltered

    by a selector

    Added in version 10

    parents(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the parents() method allows usto search through the ancestors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements ordered from immediate parent on up the elementsare returned in order f rom the closest parent to the outer ones The parents() and parent()methods are similar except that the lat ter only t ravels a single level up the DOM tree

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a basic nested list on it

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    If we begin at item A we can f ind its ancestors

    $( l i 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 onup the DOM tree all the way to the lthtmlgt element) Since we do not supply a selectorexpression 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

    Example 1 Find all parent elements of each b

    Javascript

    var parentEls = $(b)parents() map(function () return thistagName ) get()join( )$(b)append(ltstronggt + parentEls + ltstronggt)

    CSS

    b span p html body padding 5em border 1px solid b colorblue strong colorred

    HTML

    ltdivgt ltpgt ltspangt ltbgtMy parents are ltbgt ltspangt

    ltpgt ltdivgt

    Example 2 Click to f ind all unique div parent elements of each span

    Javascript

    function showParents() $(div)css(border-color white) var len = $(spanselected) parents(div) css(border 2px red solid) length $(b)text(Unique div parents + len)$(span)cl ick(function () $(this)toggleClass(selected) showParents())

    CSS

    p div span margin2px padding1px div border2px white solid span cursorpointer font-size12px selected colorblue b colorred displayblock font-size14px

    HTML

    ltpgt ltdivgt ltdivgtltspangtHelloltspangtltdivgt ltspangtHello Againltspangt

    ltdivgt ltdivgt ltspangtAnd Hello Againltspangt ltdivgt ltpgt

    ltbgtClick Hellos to toggle their parentsltbgt

    parent

    Get the parent of each element in the current set of matched elements opt ionally f iltered by aselector

    Added in version 10

    parent(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the parent() method allows usto search through the parents of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements The parents() and parent() methods are similar exceptthat the lat ter only t ravels a single level up the DOM tree

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a basic nested list on it

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    If we begin at item A we can f ind its parents

    $( l i 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 selectorexpression the parent element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

    Example 1 Shows the parent of each element as (parent gt child) Check the View Source tosee the raw html

    Javascript

    $( documentbody)each(function () var parentTag = $(this)parent()get(0)tagName $(this)prepend(documentcreateTextNode(parentTag + gt )) )

    CSS

    divp margin10px

    HTML

    ltdivgtdiv ltspangtspan ltspangt ltbgtb ltbgt

    ltdivgt ltpgtp ltspangtspan ltemgtem ltemgt ltspangt ltpgt

    ltdivgtdiv ltstronggtstrong ltspangtspan ltspangt ltemgtem ltbgtb ltbgt ltemgt

    ltstronggt ltbgtb ltbgt ltdivgt

    Example 2 Find the parent element of each paragraph with a class selected

    Javascript

    $(p)parent(selected)css(background yellow)

    HTML

    ltdivgtltpgtHelloltpgtltdivgt

    ltdiv class=selectedgtltpgtHello Againltpgtltdivgt

    offsetParent

    Get the closest ancestor element that is posit ioned

    Added in version 126

    offsetParent()jQuery

    Given a jQuery object that represents a set of DOM elements the of fsetParent() methodallows us to search through the ancestors of these elements in the DOM tree and construct anew jQuery object wrapped around the closest posit ioned ancestor An element is said to beposit ioned if it has a CSS posit ion at t ribute of relat ive absolute or f ixed This informat ion isuseful for calculat ing of fsets for performing animat ions and placing objects on the page

    Consider a page with a basic nested list on it with a posit ioned element

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    If we begin at item A we can f ind its posit ioned ancestor

    $( l i item-a)offsetParent()css(background-color red)

    This will change the color of list item II which is posit ioned

    Example 1 Find the of fsetParent of item A

    Javascript

    $( l i item-a)offsetParent()css(background-color red)

    HTML

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igt ltulgt

    nextAll

    Get all following siblings of each element in the set of matched elements opt ionally f iltered bya selector

    Added in version 12

    nextAll(selector)jQuery

    selectorString (opt ional) A string containing a selector expression to match elementsagainst

    Given a jQuery object that represents a set of DOM elements the nextAll() method allows usto search through the successors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    If we begin at the third item we can f ind the elements which come after it

    $( l i 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 aselector 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

    Example 1 Locate all the divs af ter the f irst and give them a class

    Javascript

    $(divfirst)nextAll()addClass(after)

    CSS

    div width 80px height 80px background abc border 2px solid black margin 10px float left divafter border-color red

    HTML

    ltdivgtfirstltdivgt ltdivgtsiblingltdivgtchildltdivgtltdivgt ltdivgtsiblingltdivgt

    ltdivgtsiblingltdivgt

    Example 2 Locate all the paragraphs af ter the second child in the body and give them a class

    Javascript

    $(nth-child(1))nextAll(p)addClass(after)

    CSS

    div p width 60px height 60px background abc border 2px solid black margin 10px float left after border-color red

    HTML

    ltpgtpltpgt

    ltdivgtdivltdivgt ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt

    ltpgtpltpgt ltdivgtdivltdivgt

    next

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

    Added in version 10

    next(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the next() method allows us tosearch through the immediately following sibling of these elements in the DOM tree andconstruct a new jQuery object f rom the matching elements

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the immediately following sibling matches the selector it remains in the newlyconstructed jQuery object otherwise it is excluded

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    If we begin at the third item we can f ind the element which comes just af ter it

    $( l i 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 hadsupplied one the element would be tested for a match before it was included

    Example 1 Find the very next sibling of each disabled button and change its text this button isdisabled

    Javascript

    $(button[disabled])next()text(this button is disabled)

    CSS

    span colorblue font-weightbold button width100px

    HTML

    ltdivgtltbutton disabled=disabledgtFirstltbuttongt - ltspangtltspangtltdivgt ltdivgtltbuttongtSecondltbuttongt - ltspangtltspangtltdivgt

    ltdivgtltbutton disabled=disabledgtThirdltbuttongt - ltspangtltspangtltdivgt

    Example 2 Find the very next sibling of each paragraph Keep only the ones with a classselected

    Javascript

    $(p)next(selected)css(background yellow)

    HTML

    ltpgtHelloltpgt

    ltp class=selectedgtHello Againltpgt ltdivgtltspangtAnd Againltspangtltdivgt

    find

    Get the descendants of each element in the current set of matched elements f iltered by aselector jQuery object or element

    Added in version 16

    f ind(element)jQuery

    elementElement An element to match elements against

    Given a jQuery object that represents a set of DOM elements the f ind() method allows us tosearch through the descendants of these elements in the DOM tree and construct a newjQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree

    The f irst signature for the f ind()method accepts a selector expression of the same type thatwe can pass to the $() funct ion The elements will be f iltered by test ing whether they match thisselector

    Consider a page with a basic nested list on it

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    If we begin at item II we can f ind list items within it

    $( l i item-ii )find( l i )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 IImatches the selector expression it is not included in the results only descendants areconsidered candidates for the match

    Unlike in the rest of the tree traversal methods the selector expression is requiredin a call to find() If we need to retrieve all of the descendant elements we canpass in the universal selector to accomplish this

    Selector context is implemented with the f ind() method therefore $(liitem-ii)f ind(li) isequivalent to $(li liitem-ii)

    As of jQuery 16 we can also f ilter the select ion with a given jQuery collect ion or element Withthe same nested list as above if we start with

    var $allListElements = $( l i )

    And then pass this jQuery object to f ind

    $( l i item-ii )find( $allListElements )

    This will return a jQuery collect ion which contains only the list elements that are descendantsof item II

    Similarly an element may also be passed to f ind

    var item1 = $( l i item-1)[0]$( l i item-ii )find( item1 )css(background-color red)

    The result of this call would be a red background on item 1

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

    Javascript

    $(p)find(span)css(color red)

    HTML

    ltpgtltspangtHelloltspangt how are youltpgtltpgtMe Im ltspangtgoodltspangtltpgt

    Example 2 A select ion using a jQuery collect ion of all span tags Only spans within p tags arechanged to red while others are lef t blue

    CSS

    span color blue

    Javascript

    var $spans = $(span) $(p)find( $spans )css(color red)

    HTML

    ltpgtltspangtHelloltspangt how are youltpgt ltpgtMe Im ltspangtgoodltspangtltpgt ltdivgtDid you ltspangteatltspangt yetltdivgt

    Example 3 Add spans around each word then add a hover and italicize words with the let ter t

    Javascript

    var newText = $(p)text()split( )join(ltspangt ltspangt) newText = ltspangt + newText + ltspangt

    $(p)html( newText ) find(span) hover(function() $(this)addClass(hil ite) function() $(this)removeClass(hil ite) ) end() find(contains(t)) css(font-style ital ic font-weightbolder)

    CSS

    p font-size20px width200px cursordefault colorblue font-weightbold margin0 10px hi l ite backgroundyellow

    HTML

    ltpgt When the day is short find that which matters to you or stop believing ltpgt

    contents

    Get the children of each element in the set of matched elements including text and commentnodes

    Added in version 12

    contents()jQuery

    Given a jQuery object that represents a set of DOM elements the contents() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The contents() and children() methods aresimilar except that the former includes text nodes as well as HTML elements in the result ingjQuery object

    The contents() method can also be used to get the content document of an if rame if theif rame is on the same domain as the main page

    Consider a simple ltdivgt with a number of text nodes each of which is separated by two linebreak elements (ltbr gt)

    ltdiv class=containergt Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ltbr gtltbr gt Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut al iquip ex ea commodo consequat ltbr gt ltbr gt Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariaturltdivgt

    We can employ the contents() method to help convert this blob of text into three well-formedparagraphs

    $(container)contents()fi lter(function() return thisnodeType == 3) wrap(ltpgtltpgt)end()fi lter(br) remove()

    This code f irst retrieves the contents of ltdiv class=containergt and then f ilters it for textnodes which are wrapped in paragraph tags This is accomplished by test ing the nodeTypeproperty of the element This DOM property holds a numeric code indicat ing the nodes typetext nodes use the code 3 The contents are again f iltered this t ime for ltbr gt elements andthese elements are removed

    Example 1 Find all the text nodes inside a paragraph and wrap them with a bold tag

    Javascript

    $(p)contents()fi lter(function() return thisnodeType = 1 )wrap(ltbgt)

    HTML

    ltpgtHello lta href=httpejohnorggtJohnltagt how are you doingltpgt

    Example 2 Change the background colour of links inside of an if rame

    Javascript

    $(frameDemo)contents()find(a)css(background-colorBADA55)

    HTML

    ltiframe src=httpapijquerycom width=80 height=600 id=frameDemogtltiframegt

    closest

    Get the f irst ancestor element that matches the selector beginning at the current element andprogressing up through the DOM tree

    Added in version 16

    closest(element)jQuery

    elementElement An element to match elements against

    Given a jQuery object that represents a set of DOM elements the closest() method allows usto search through these elements and their ancestors in the DOM tree and construct a newjQuery object f rom the matching elements The parents() and closest() methods are similar inthat they both t raverse up the DOM tree The dif ferences between the two though subt le aresignif icant

    closest() parents()

    Begins with thecurrent element

    Begins with the parent element

    Travels up the DOMtree unt il it f inds amatch for the suppliedselector

    Travels up the DOM tree to the document s root elementadding each ancestor element to a temporary collect ion it thenf ilters that collect ion based on a selector if one is supplied

    The returned jQueryobject contains zeroor one element

    The returned jQuery object contains zero one or mult ipleelements

    ltul id=one class=level-1gt ltli class=item-igtIltl igt ltli id=ii class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    Suppose we perform a search for ltulgt elements start ing at item A

    $( l i item-a)closest(ul ) css(background-color red)

    This will change the color of the level-2 ltulgt since it is the f irst encountered when traveling upthe DOM tree

    Suppose we search for an ltligt element instead

    $( l i item-a)closest( l i ) css(background-color red)

    This will change the color of list item A The closest() method begins its search with theelement itself before progressing up the DOM tree and stops when item A matches theselector

    We can pass in a DOM element as the context within which to search for the closest element

    var l istItemII = documentgetElementById( i i )$( l i item-a)closest(ul l istItemII) css(background-color red)$( l i item-a)closest(one l istItemII) css(background-color green)

    This will change the color of the level-2 ltulgt because it is both the f irst ltulgt ancestor of listitem A and a descendant of list item II It will not change the color of the level-1 ltulgt howeverbecause it is not a descendant of list item II

    Example 1 Show how event delegat ion can be done with closest The closest list elementtoggles a yellow background when it or its descendent is clicked

    Javascript

    $( document )bind(click function( e ) $( etarget )closest(l i)toggleClass(hil ight) )

    CSS

    l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

    HTML

    ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

    Example 2 Pass a jQuery object to closest The closest list element toggles a yellowbackground when it or its descendent is clicked

    Javascript

    var $listElements = $(l i)css(color blue) $( document )bind(click function( e ) $( etarget )closest( $listElements )toggleClass(hil ight) )

    CSS

    l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

    HTML

    ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

    closest

    Gets an array of all the elements and selectors matched against the current element upthrough the DOM tree

    Added in version 14

    closest(selectors context)Array

    selectorsArray An array or string containing a selector expression to match elementsagainst (can also be a jQuery object)

    context Element (opt ional) A DOM element within which a matching element may befound If no context is passed in then the context of the jQuery setwill be used instead

    This method is primarily meant to be used internally or by plugin authors

    Example 1 Show how event delegat ion can be done with closest

    Javascript

    var close = $(l i first)closest([ul body]) $each(close function(i) $(l i)eq(i)html( thisselector + + thiselemnodeName ) )

    CSS

    HTML

    ltulgtltligtltligtltligtltligtltulgt

    children

    Get the children of each element in the set of matched elements opt ionally f iltered by aselector

    Added in version 10

    children(selector)jQuery

    selectorSelector (opt ional) A string containing a selector expression to matchelements against

    Given a jQuery object that represents a set of DOM elements the children() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree Note also that like mostjQuery methods children() does not return text nodes to get all children including text andcomment nodes use contents()

    The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

    Consider a page with a basic nested list on it

    ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

    If we begin at the level-2 list we can f ind its children

    $(ullevel-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 aselector expression all of the children are part of the returned jQuery object If we had suppliedone only the matching items among these three would be included

    Example 1 Find all children of the clicked element

    Javascript

    $(container)cl ick(function (e) $()removeClass(hil ite) var $kids = $(etarget)children() var len = $kidsaddClass(hil ite)length

    $(results spanfirst)text(len) $(results spanlast)text(etargettagName)

    epreventDefault() return false )

    CSS

    body font-size16px font-weightbolder div width130px height82px margin10px floatleft border1px solid blue padding4px container widthauto height105px margin0 floatnone bordernone hi l ite border-colorred results displayblock colorred p margin10px border1px solid transparent span colorblue border1px solid transparent input width100px em border1px solid transparent a border1px solid transparent b border1px solid transparent button border1px solid transparent

    HTML

    ltdiv id=containergt

    ltdivgt ltpgtThis ltspangtis the ltemgtwayltemgt weltspangt write ltemgttheltemgt demoltpgt

    ltdivgt ltdivgt lta href=gtltbgtwltbgtritltbgteltbgtltagt the ltspangtdemoltspangt ltbuttongtwrite theltbuttongt demo ltdivgt

    ltdivgt This ltspangtthe way we ltemgtwriteltemgt the ltemgtdemoltemgt soltspangt

    ltinput type=text value=early gt in ltdivgt ltpgt ltspangttltspangthe ltspangtmltspangtorning ltspan id=resultsgtFound ltspangt0ltspangt children in ltspangtTAGltspangtltspangt

    ltpgt ltdivgt

    Example 2 Find all children of each div

    Javascript

    $(div)children()css(border-bottom 3px double red)

    CSS

    body font-size16px font-weightbolder span colorblue p margin5px 0

    HTML

    ltpgtHello (this is a paragraph)ltpgt

    ltdivgtltspangtHello Again (this span is a child of the a div)ltspangtltdivgt ltpgtAnd ltspangtAgainltspangt (in another paragraph)ltpgt

    ltdivgtAnd One Last ltspangtTimeltspangt (most text directly in a div)ltdivgt

    Example 3 Find all children with a class selected of each div

    Javascript

    $(div)children(selected)css(color blue)

    CSS

    body font-size16px font-weightbolder p margin5px 0

    HTML

    ltdivgt ltspangtHelloltspangt ltp class=selectedgtHello Againltpgt ltdiv class=selectedgtAnd Againltdivgt

    ltpgtAnd One Last Timeltpgt ltdivgt

    add

    Add elements to the set of matched elements

    Added in version 14

    add(selector context)jQuery

    selectorSelector A string represent ing a selector expression to f ind addit ionalelements to add to the set of matched elements

    context Element The point in the document at which the selector should beginmatching similar to the context argument of the $(selector context)method

    Given a jQuery object that represents a set of DOM elements the add() method constructs anew jQuery object f rom the union of those elements and the ones passed into the methodThe argument to add() can be pret ty much anything that $() accepts including a jQueryselector 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 avariable for later use For example

    $(p)add(div)addClass(widget)var pdiv = $(p)add(div)

    The following will not save the added elements because the add() method creates a new setand leaves the original set in pdiv unchanged

    var pdiv = $(p)pdivadd(div) WRONG pdiv wil l not change

    Consider a page with a simple list and a paragraph following it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligtltulgtltpgta paragraphltpgt

    We can select the list items and then the paragraph by using either a selector or a reference tothe DOM element itself as the add() methods argument

    $( l i )add(p)css(background-color red)

    Or

    $( l i )add(documentgetElementsByTagName(p)[0]) css(background-color red)

    The result of this call is a red background behind all four elements Using an HTML snippet asthe add() methods argument (as in the third version) we can create addit ional elements on thef ly and add those elements to the matched set of elements Let s say for example that wewant to alter the background of the list items along with a newly created paragraph

    $( l i )add(ltp id=newgtnew paragraphltpgt) css(background-color red)

    Although the new paragraph has been created and its background color changed it st ill doesnot appear on the page To place it on the page we could add one of the insert ion methods tothe chain

    As of jQuery 14 the results f rom add() will always be returned in document order (rather than asimple concatenat ion)

    Note To reverse the add() you can use not( elements | selector ) to remove elements f rom thejQuery results or end() to return to the select ion before you added

    Example 1 Finds all divs and makes a border Then adds all paragraphs to the jQuery object toset their backgrounds yellow

    Javascript

    $(div)css(border 2px solid red) add(p) css(background yellow)

    CSS

    div width60px height60px margin10px floatleft p clearleft font-weightbold font-size16px colorblue margin0 10px padding2px

    HTML

    ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    ltpgtAdded this (notice no border)ltpgt

    Example 2 Adds more elements matched by the given expression to the set of matchedelements

    Javascript

    $(p)add(span)css(background yellow)

    HTML

    ltpgtHelloltpgtltspangtHello Againltspangt

    Example 3 Adds more elements created on the f ly to the set of matched elements

    Javascript

    $(p)clone()add(ltspangtAgainltspangt)appendTo(documentbody)

    HTML

    ltpgtHelloltpgt

    Example 4 Adds one or more Elements to the set of matched elements

    Javascript

    $(p)add(documentgetElementById(a))css(background yellow)

    HTML

    ltpgtHelloltpgtltspan id=agtHello Againltspangt

    Example 5 Demonstrates how to add (or push) elements to an exist ing collect ion

    Javascript

    var collection = $(p) capture the new collectioncollection = collectionadd(documentgetElementById(a))collectioncss(background yellow)

    HTML

    ltpgtHelloltpgtltspan id=agtHello Againltspangt

    not

    Remove elements f rom the set of matched elements

    Added in version 14

    not(funct ion(index))jQuery

    funct ion(index)Funct ion A funct ion used as a test for each element in the set this isthe current DOM element

    Given a jQuery object that represents a set of DOM elements the not() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element the elements that dont match the selector will be included in the result

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    We can apply this method to the set of list items

    $( l i )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 not() method allows us to remove elements f rom the matched setassuming we have found those elements previously by some other means For examplesuppose our list had an id applied to one of its items

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli id=notligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    We can fetch the third list item using the nat ive JavaScript getElementById() funct ion thenremove it f rom a jQuery object

    $( l i )not(documentgetElementById(notl i )) css(background-color red)

    This statement changes the color of items 1 2 4 and 5 We could have accomplished thesame thing with a simpler jQuery expression but this technique can be useful when forexample other libraries provide references to plain DOM nodes

    As of jQuery 14 the not() method can take a funct ion as its argument in the same way thatf ilter() does Elements for which the funct ion returns t rue are excluded from the f iltered set allother elements are included

    Example 1 Adds a border to divs that are not green or blue

    Javascript

    $(div)not(green blueone) css(border-color red)

    CSS

    div width50px height50px margin10px floatleft backgroundyellow border2px solid white green background8f8 gray backgroundccc blueone background99f

    HTML

    ltdivgtltdivgt ltdiv id=blueonegtltdivgt ltdivgtltdivgt ltdiv class=greengtltdivgt

    ltdiv class=greengtltdivgt ltdiv class=graygtltdivgt ltdivgtltdivgt

    Example 2 Removes the element with the ID selected f rom the set of all paragraphs

    Javascript

    $(p)not( $(selected)[0] )

    Example 3 Removes the element with the ID selected f rom the set of all paragraphs

    Javascript

    $(p)not(selected)

    Example 4 Removes all elements that match div pselected f rom the total set of allparagraphs

    Javascript

    $(p)not($(div pselected))

    map

    Pass each element in the current matched set through a funct ion producing a new jQueryobject containing the return values

    Added in version 12

    map(callback(index domElement))jQuery

    callback(indexdomElement)Funct ion

    A funct ion object that will be invoked for each element inthe current set

    As the return value is a jQuery-wrapped array it s very common to get() the returned object towork with a basic array

    The map() method is part icularly useful for gett ing or set t ing the value of a collect ion ofelements Consider a form with a set of checkboxes in it

    ltform method=post action=gt ltfieldsetgt ltdivgt ltlabel for=twogt2ltlabelgt ltinput type=checkbox value=2 id=two name=number[]gt ltdivgt ltdivgt ltlabel for=fourgt4ltlabelgt ltinput type=checkbox value=4 id=four name=number[]gt ltdivgt ltdivgt ltlabel for=sixgt6ltlabelgt ltinput type=checkbox value=6 id=six name=number[]gt ltdivgt ltdivgt ltlabel for=eightgt8ltlabelgt ltinput type=checkbox value=8 id=eight name=number[]gt ltdivgt ltfieldsetgtltformgt

    We can get a comma-separated list of checkbox IDs

    $(checkbox)map(function() return thisid)get()join( )

    The result of this call is the string twofoursixeight

    Within the callback funct ion this refers to the current DOM element for each iterat ion Thefunct ion can return an individual data item or an array of data items to be inserted into theresult ing set If an array is returned the elements inside the array are inserted into the set If thefunct ion returns null or undef ined no element will be inserted

    Example 1 Build a list of all the values within a form

    Javascript

    $(p)append( $(input)map(function() return $(this)val() )get()join( ) )

    CSS

    p colorred

    HTML

    ltpgtltbgtValues ltbgtltpgt ltformgt ltinput type=text name=name value=Johngt

    ltinput type=text name=password value=passwordgt ltinput type=text name=url value=httpejohnorggt

    ltformgt

    Example 2 A contrived example to show some funct ionality

    Javascript

    var mappedItems = $(l i)map(function (index) var replacement = $(ltligt)text($(this)text())get(0) i f (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$(ltligt)get(0)] $(replacement[0])append(ltbgt - Altbgt) $(replacement[1])append(Extra ltbgt - Bltbgt)

    replacement wil l be a dom element null or an array of dom elements return replacement)$(results)append(mappedItems)

    CSS

    body font-size16px ul floatleft margin0 30px colorblue results colorred

    HTML

    ltulgt ltligtFirstltl igt ltligtSecondltligt ltligtThirdltligt

    ltligtFourthltligt ltligtFifthltligt ltulgt ltul id=resultsgt

    ltulgt

    Example 3 Equalize the heights of the divs

    Javascript

    $fnequalizeHeights = function() var maxHeight = thismap(function(ie) return $(e)height() )get() return thisheight( Mathmaxapply(this maxHeight) )

    $( input)cl ick(function() $(div)equalizeHeights())

    CSS

    div width 40px floatleft input clearleft

    HTML

    ltinput type=button value=equalize div heightsgt

    ltdiv style=backgroundred height 40px gtltdivgtltdiv style=backgroundgreen height 70pxgtltdivgtltdiv style=backgroundblue height 50px gtltdivgt

    is

    Check the current matched set of elements against a selector element or jQuery object andreturn t rue if at least one of these elements matches the given arguments

    Added in version 16

    is(element)Boolean

    elementElement An element to match the current set of elements against

    Unlike other f iltering methods is() does not create a new jQuery object Instead it allows youto test the contents of a jQuery object without modif icat ion This is of ten useful insidecallbacks such as event handlers

    Suppose you have a list with two of its items containing a child element

    ltulgt ltligtlist ltstronggtitem 1ltstronggtltligt ltligtltspangtlist item 2ltspangtltligt ltligtlist item 3ltligtltulgt

    You can at tach a click handler to the ltulgt element and then limit the code to be triggered onlywhen a list item itself not one of its children is clicked

    $(ul)cl ick(function(event) var $target = $(eventtarget) i f ( $targetis( l i) ) $targetcss(background-color red) )

    Now when the user clicks on the word list in the f irst item or anywhere in the third item theclicked list item will be given a red background However when the user clicks on item 1 in thef irst item or anywhere in the second item nothing will occur because in those cases the targetof the event would be ltstronggt or ltspangt respect ively

    Be aware that for selector strings with posit ional selectors such as f irst gt() or even theposit ional f iltering is done against the jQuery object passed to is() not against the containingdocument So for the HTML shown above an expression such as $(lif irst)is(lilast) returnstrue but $(lif irst-child)is(lilast-child) returns false

    Using a Function

    The second form of this method evaluates expressions related to elements based on afunct ion rather than a selector For each element if the funct ion returns t rue is() returns t rueas well For example given a somewhat more involved HTML snippet

    ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

    You can at tach a click handler to every ltligt that evaluates the number of ltstronggt elementswithin the clicked ltligt at that t ime like so

    $(l i)cl ick(function() var $li = $(this) isWithTwo = $liis(function() return $(strong this)length === 2 ) i f ( isWithTwo ) $l i css(background-color green) else $l i css(background-color red) )

    Example 1 Shows a few ways is() can be used inside an event handler

    Javascript

    $(div)one(cl ick function () i f ($(this)is(first-child)) $(p)text(Its the first div) else if ($(this)is(bluered)) $(p)text(Its a blue or red div) else if ($(this)is(contains(Peter))) $(p)text(Its Peter) else $(p)html(Its nothing ltemgtspecialltemgt) $(p)hide()sl ideDown(slow) $(this)css(border-style inset cursordefault) )

    CSS

    div width60px height60px margin5px floatleft border4px outset backgroundgreen text-aligncenter font-weightbolder cursorpointer blue backgroundblue red backgroundred span colorwhite font-size16px p colorred font-weightbolder backgroundyellow margin3px clearleft displaynone

    HTML

    ltdivgtltdivgtltdiv class=bluegtltdivgtltdivgtltdivgtltdiv class=redgtltdivgt

    ltdivgtltbrgtltspangtPeterltspangtltdivgtltdiv class=bluegtltdivgtltpgtampnbspltpgt

    Example 2 Returns t rue because the parent of the input is a form element

    Javascript

    var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

    CSS

    div colorred

    HTML

    ltformgtltinput type=checkbox gtltformgtltdivgtltdivgt

    Example 3 Returns false because the parent of the input is a p element

    Javascript

    var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

    CSS

    div colorred

    HTML

    ltformgtltpgtltinput type=checkbox gtltpgtltformgt ltdivgtltdivgt

    Example 4 Checks against an exist ing collect ion of alternat ing list elements Blue alternat inglist elements slide up while others turn red

    Javascript

    var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() var $li = $(this) i f ( $l i is( $alt ) ) $l i sl ideUp() else $l i css(background red) )

    CSS

    l i cursorpointer

    HTML

    ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

    Example 5 An alternate way to achieve the above example using an element rather than ajQuery object Checks against an exist ing collect ion of alternat ing list elements Bluealternat ing list elements slide up while others turn red

    Javascript

    var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() i f ( $altis( this ) ) $(this)sl ideUp() else $(this)css(background red) )

    CSS

    l i cursorpointer

    HTML

    ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

    eq

    Reduce the set of matched elements to the one at the specif ied index

    Added in version 14

    eq(-index)jQuery

    -indexInteger

    An integer indicat ing the posit ion of the element count ing backwardsfrom the last element in the set

    Given a jQuery object that represents a set of DOM elements the eq() method constructs anew jQuery object f rom one element within that set The supplied index ident if ies the posit ionof this element in the set

    Consider a page with a simple list on it

    ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltulgt

    We can apply this method to the set of list items

    $( l i )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-basedand refers to the posit ion of the element within the jQuery object not within the DOM tree

    Providing a negat ive number indicates a posit ion start ing f rom the end of the set rather thanthe beginning For example

    $( l i )eq(-2)css(background-color red)

    This t ime list item 4 is turned red since it is two from the end of the set

    If an element cannot be found at the specif ied zero-based index the method constructs a newjQuery object with an empty set and a length property of 0

    $( l i )eq(5)css(background-color red)

    Here none of the list items is turned red since eq(5) indicates the sixth of f ive list items

    Example 1 Turn the div with index 2 blue by adding an appropriate class

    Javascript

    $(body)find(div)eq(2)addClass(blue)

    CSS

    div width60px height60px margin10px floatleft border2px solid blue blue backgroundblue

    HTML

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    filter

    Reduce the set of matched elements to those that match the selector or pass the funct ionstest

    Added in version 14

    f ilter(jQuery object)jQuery

    jQueryobject Object

    An exist ing jQuery object to match the current set of elementsagainst

    Given a jQuery object that represents a set of DOM elements the f ilter() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is tested

    new jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element all elements matching the selector will be included in the result

    Consider a page with a simple list on it

    list item 1

    list item 2

    list item 3

    list item 4

    list item 5

    list item 6

    We can apply this method to the set of list items

    $( l i )fi lter( 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 even and odd use 0-based indexing)

    Using a Filter Function

    The second form of this method allows us to f ilter elements against a funct ion rather than aselector For each element if the funct ion returns t rue (or a t ruthy value) the element will beincluded in the f iltered set otherwise it will be excluded Suppose we have a somewhat moreinvolved HTML snippet

    ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltligtlist item 6ltligtltulgt

    We can select the list items then f ilter them based on their contents

    $( l i )fi lter(function(index) return $(strong this)length == 1)css(background-color red)

    This code will alter the f irst list item only as it contains exact ly one ltstronggt tag Within the

    f ilter funct ion this refers to each DOM element in turn The parameter passed to the funct iontells us the index of that DOM element within the set matched by the jQuery object

    We can also take advantage of the index passed through the funct ion which indicates the 0-based posit ion of the element within the unf iltered set of matched elements

    $( l i )fi lter(function(index) return index 3 == 2)css(background-color red)

    This alterat ion to the code will cause the third and sixth list items to be highlighted as it usesthe modulus operator () to select every item with an index value that when divided by 3 hasa remainder of 2

    Example 1 Change the color of all divs then add a border to those with a middle class

    Javascript

    $(div)css(background c8ebcc) fi lter(middle) css(border-color red)

    CSS

    div width60px height60px margin5px floatleft border2px white solid

    HTML

    ltdivgtltdivgt

    ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt

    ltdivgtltdivgt

    Example 2 Change the color of all divs then add a border to the second one (index == 1) andthe div with an id of fourth

    Javascript

    $(div)css(background b4b0da) fi lter(function (index) return index == 1 || $(this)attr( id) == fourth ) css(border 3px double red)

    CSS

    div width60px height60px margin5px floatleft border3px white solid

    HTML

    ltdiv id=firstgtltdivgt ltdiv id=secondgtltdivgt ltdiv id=thirdgtltdivgt

    ltdiv id=fourthgtltdivgt ltdiv id=fifthgtltdivgt ltdiv id=sixthgtltdivgt

    Example 3 Select all divs and f ilter the select ion with a DOM element keeping only the one withan id of unique

    Javascript

    $(div)fi lter( documentgetElementById(unique) )

    Example 4 Select all divs and f ilter the select ion with a jQuery object keeping only the one withan id of unique

    Javascript

    $(div)fi lter( $(unique) )

    Attributes

    removeProp

    Remove a property for the set of matched elements

    Added in version 16

    removeProp(propertyName)jQuery

    propertyNameString The name of the property to set

    The removeProp() method removes propert ies set by the prop() method

    With some built -in propert ies of a DOM element or window object browsers may generate anerror if an at tempt is made to remove the property jQuery f irst assigns the value undef ined tothe property and ignores any error the browser generates In general it is only necessary toremove custom propert ies that have been set on an object and not built -in (nat ive) propert ies

    Note Do not use this method to remove nat ive propert ies such as checked disabled orselected This will remove the property completely and once removed cannot be added againto element Use prop() to set these propert ies to false instead

    Example 1 Set a numeric property on a paragraph and then remove it

    Javascript

    var $para = $(p)$paraprop(luggageCode 1234)$paraappend(The secret luggage code is String($paraprop(luggageCode)) )$pararemoveProp(luggageCode)$paraappend(Now the secret luggage code is String($paraprop(luggageCode)) )

    CSS

    img padding10px div colorred font-size24px

    HTML

    ltpgtltpgt

    prop

    Get the value of a property for the f irst element in the set of matched elements

    Added in version 16

    prop(propertyName)String

    propertyNameString The name of the property to get

    The prop() method gets the property value for only the first element in the matched set Itreturns undef ined for the value of a property that has not been set or if the matched set hasno elements To get the value for each element individually use a looping construct such asjQuerys each() or map() method

    The dif ference between attributes and properties can be important in specif ic situat ions BeforejQuery 16 the at t r() method sometimes took property values into account when retrievingsome attributes which could cause inconsistent behavior As of jQuery 16 the prop() methodprovides a way to explicit ly retrieve property values while at t r() retrieves at t ributes

    For example selectedIndex tagName nodeName nodeType ownerDocumentdefaultChecked and defaultSelected should be retrieved and set with the prop() method Priorto jQuery 16 these propert ies were retrievable with the at t r() method but this was not withinthe scope of at t r These do not have corresponding at t ributes and are only propert ies

    Concerning boolean at t ributes consider a DOM element def ined by the HTML markup ltinputtype=checkbox checked=checked gt and assume it is in a JavaScript variable named elem

    elemchecked t rue (Boolean) Will change with checkbox state

    $(elem)prop(checked) t rue (Boolean) Will change with checkbox state

    elemgetAttribute(checked)checked (String) Init ial state of the checkbox doesnot change

    $(elem)attr(checked)(16)checked (String) Init ial state of the checkbox doesnot change

    $(elem)attr(checked)(161+) checked (String) Will change with checkbox state

    $(elem)attr(checked)(pre-16)

    t rue (Boolean) Changed with checkbox state

    According to the W3C forms specif icat ion the checked at t ribute is a boolean attribute whichmeans the corresponding property is t rue if the at t ribute is present at allacirceurordquoeven if for examplethe at t ribute has no value or an empty string value The preferred cross-browser-compat ibleway to determine if a checkbox is checked is to check for a t ruthy value on the element sproperty using one of the following

    if ( elemchecked )

    if ( $(elem)prop(checked) )

    if ( $(elem)is(checked) )

    If using jQuery 16 the code if ( $(elem)at t r(checked) ) will retrieve the actual content attributewhich does not change as the checkbox is checked and unchecked It is meant only to storethe default or init ial value of the checked property To maintain backwards compatability theat t r() method in jQuery 161+ will retrieve and update the property for you so no code forboolean at t ributes is required to be changed to prop() Nevertheless the preferred way toretrieve a checked value is with one of the opt ions listed above To see how this works in thelatest jQuery checkuncheck the checkbox in the example below

    Example 1 Display the checked property and at t ribute of a checkbox as it changes

    Javascript

    $(input)change(function() var $input = $(this) $(p)html(attr(checked) ltbgt + $inputattr(checked) + ltbgtltbrgt + prop(checked) ltbgt + $inputprop(checked) + ltbgtltbrgt + is( checked) ltbgt + $inputis( checked) ) + ltbgt)change()

    CSS

    p margin 20px 0 0 b color blue

    HTML

    ltinput id=check1 type=checkbox checked=checkedgtltlabel for=check1gtCheck meltlabelgtltpgtltpgt

    prop

    Set one or more propert ies for the set of matched elements

    Added in version 16

    prop(propertyName funct ion(index oldPropertyValue))jQuery

    propertyNameString The name of the property to set

    funct ion(indexoldPropertyValue)Funct ion

    A funct ion returning the value to set Receives the indexposit ion of the element in the set and the old propertyvalue as arguments Within the funct ion the keyword thisrefers to the current element

    The prop() method is a convenient way to set the value of propert iesacirceurordquoespecially whensett ing mult iple propert ies using values returned by a funct ion or set t ing values on mult ipleelements at once It should be used when sett ing selectedIndex tagName nodeNamenodeType ownerDocument defaultChecked or defaultSelected Since jQuery 16 thesepropert ies can no longer be set with the at t r() method They do not have correspondingattributes and are only propert ies

    Propert ies generally af fect the dynamic state of a DOM element without changing theserialized HTML attribute Examples include the value property of input elements the disabledproperty of inputs and buttons or the checked property of a checkbox The prop() methodshould be used to set disabled and checked instead of the at t r() method The val() methodshould be used for gett ing and sett ing value

    $(input)prop(disabled false)$(input)prop(checked true)$(input)val(someValue)

    Important the removeProp() method should not be used to set these propert ies to false Oncea nat ive property is removed it cannot be added again See removeProp() for moreinformat ion

    Computed property values

    By using a funct ion to set propert ies you can compute the value based on other propert ies ofthe element For example to toggle all checkboxes based of f their individual values

    $(input[type=checkbox])prop(checked function( i val ) return val)

    Note If nothing is returned in the setter funct ion (ie funct ion(index prop)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

    Example 1 Disable all checkboxes on the page

    Javascript

    $(input[type=checkbox])prop( disabled true)

    CSS

    img padding10px div colorred font-size24px

    HTML

    ltinput type=checkbox checked=checked gt ltinput type=checkbox gt ltinput type=checkbox gt ltinput type=checkbox checked=checked gt

    val

    Get the current value of the f irst element in the set of matched elements

    Added in version 10

    val()String Number Array

    The val() method is primarily used to get the values of form elements In the case of ltselectmult iple=mult iplegt elements the val() method returns an array containing each selectedopt ion

    For selects and checkboxes you can also use the selected and checked selectors to get atvalues for example

    $(selectfoo optionselected)val() get the value from a dropdown select$(selectfoo)val() get the value from a dropdown select even easier$( inputcheckboxchecked)val() get the value from a checked checkbox$( inputradio[name=bar]checked)val() get the value from a set of radio buttons

    Example 1 Get the single value from a single select and an array of values from a mult ipleselect and display their values

    Javascript

    function displayVals() var singleValues = $(single)val() var multipleValues = $(multiple)val() || [] $(p)html(ltbgtSingleltbgt + singleValues + ltbgtMultipleltbgt + multipleValuesjoin( ))

    $(select)change(displayVals) displayVals()

    CSS

    p colorred margin4px b colorblue

    HTML

    ltpgtltpgt ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

    ltselectgt ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

    ltoption selected=selectedgtMultiple3ltoptiongt ltselectgt

    Example 2 Find the value of an input box

    Javascript

    $(input)keyup(function () var value = $(this)val() $(p)text(value) )keyup()

    CSS

    p colorblue margin8px

    HTML

    ltinput type=text value=some textgt ltpgtltpgt

    val

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

    Added in version 14

    val(funct ion(index value))jQuery

    funct ion(indexvalue)Funct ion

    A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the old valueas arguments

    This method is typically used to set the values of form f ields

    Passing an array of element values allows matching ltinput type=checkboxgt ltinputtype=radiogt and ltopt iongts inside of n ltselect mult iple=mult iplegt to be selected In the caseof ltinput type=radiogts that are part of a radio group and ltselect mult iple=mult iplegt theother elements will be deselected

    The val() method allows us to set the value by passing in a funct ion As of jQuery 14 thefunct ion is passed two arguments the current element s index and its current value

    $( inputtextitems)val(function(index value) return value + + thisclassName)

    This example appends the string items to the text inputs values

    Example 1 Set the value of an input box

    Javascript

    $(button)cl ick(function () var text = $(this)text() $(input)val(text) )

    CSS

    button margin4px cursorpointer input margin4px colorblue

    HTML

    ltdivgt ltbuttongtFeedltbuttongt ltbuttongttheltbuttongt

    ltbuttongtInputltbuttongt ltdivgt ltinput type=text value=click a button gt

    Example 2 Use the funct ion argument to modify the value of an input box

    Javascript

    $( input)bind(blur function() $(this)val(function(i val) return valtoUpperCase() ) )

    HTML

    ltpgtType something and then click or tab out of the inputltpgt ltinput type=text value=type something gt

    Example 3 Set a single select a mult iple select checkboxes and a radio button

    Javascript

    $(single)val(Single2) $(multiple)val([Multiple2 Multiple3]) $(input)val([check1check2 radio1 ])

    CSS

    body colorblue

    HTML

    ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

    ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

    ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=checkboxname value=check1gt check1 ltinput type=checkbox name=checkboxname value=check2gt check2 ltinput type=radio name=r value=radio1gt radio1 ltinput type=radio name=r value=radio2gt radio2

    html

    Get the HTML contents of the f irst element in the set of matched elements

    Added in version 10

    html()String

    This method is not available on XML documents

    In an HTML document html() can be used to get the contents of any element If the selectorexpression matches more than one element only the f irst match will have its HTML contentreturned Consider this code

    $(divdemo-container)html()

    In order for the following ltdivgts content to be retrieved it would have to be the f irst one withclass=demo-container in the document

    ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

    The result would look like this

    ltdiv class=demo-boxgtDemonstration Boxltdivgt

    This method uses the browsers innerHTML property Some browsers may not return HTML

    that exact ly replicates the HTML source in an original document For example Internet Explorersometimes leaves of f the quotes around at t ribute values if they contain only alphanumericcharacters

    Example 1 Click a paragraph to convert it f rom html to text

    Javascript

    $(p)cl ick(function () var htmlStr = $(this)html() $(this)text(htmlStr) )

    CSS

    p margin8px font-size20px colorblue cursorpointer b text-decorationunderline button cursorpointer

    HTML

    ltpgt

    ltbgtClickltbgt to change the ltspan id=taggthtmlltspangt ltpgt ltpgt

    to a ltspan id=textgttextltspangt node ltpgt ltpgt This ltbutton name=nadagtbuttonltbuttongt does nothing ltpgt

    html

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

    Added in version 14

    html(funct ion(index oldhtml))jQuery

    funct ion(indexoldhtml)Funct ion

    A funct ion returning the HTML content to set Receives the indexposit ion of the element in the set and the old HTML value asarguments jQuery empt ies the element before calling the funct ionuse the oldhtml argument to reference the previous content Withinthe funct ion this refers to the current element in the set

    The html() method is not available in XML documents

    When html() is used to set an element s content any content that was in that element iscompletely replaced by the new content Consider the following HTML

    ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

    The content of ltdiv class=demo-containergt can be set like this

    $(divdemo-container) html(ltpgtAll new content ltemgtYou betltemgtltpgt)

    That line of code will replace everything inside ltdiv class=demo-containergt

    ltdiv class=demo-containergt ltpgtAll new content ltemgtYou betltemgtltpgtltdivgt

    As of jQuery 14 the html() method allows the HTML content to be set by passing in afunct ion

    $(divdemo-container)html(function() var emph = ltemgt + $(p)length + paragraphsltemgt return ltpgtAll new content for + emph + ltpgt)

    Given a document with six paragraphs this example will set the HTML of ltdiv class=demo-containergt to ltpgtAll new content for ltemgt6 paragraphsltemgtltpgt

    This method uses the browsers innerHTML property Some browsers may not generate a DOMthat exact ly replicates the HTML source provided For example Internet Explorer prior toversion 8 will convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

    Example 1 Add some html to each div

    Javascript

    $(div)html(ltspan class=redgtHello ltbgtAgainltbgtltspangt)

    CSS

    red colorred

    HTML

    ltspangtHelloltspangt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    Example 2 Add some html to each div then immediately do further manipulat ions to theinserted html

    Javascript

    $(div)html(ltbgtWowltbgt Such excitement) $(div b)append(documentcreateTextNode()) css(color red)

    CSS

    div colorblue font-size18px

    HTML

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    toggleClass

    Add or remove one or more classes from each element in the set of matched elementsdepending on either the classs presence or the value of the switch argument

    Added in version 14

    toggleClass(funct ion(index class switch) switch)jQuery

    funct ion(indexclassswitch)Funct ion

    A funct ion that returns class names to be toggled in the classattribute of each element in the matched set Receives the indexposit ion of the element in the set the old class value and the switchas arguments

    switchBoolean (opt ional) A boolean value to determine whether the class should beadded or removed

    This method takes one or more class names as its parameter In the f irst version if an elementin the matched set of elements already has the class then it is removed if an element does nothave the class then it is added For example we can apply toggleClass() to a simple ltdivgt

    ltdiv class=tumblegtSome textltdivgt

    The f irst t ime we apply $(divtumble)toggleClass(bounce) we get the following

    ltdiv class=tumble bouncegtSome textltdivgt

    The second t ime we apply $(divtumble)toggleClass(bounce) the ltdivgt class is returned tothe single tumble value

    ltdiv class=tumblegtSome textltdivgt

    Applying toggleClass(bounce spin) to the same ltdivgt alternates between ltdiv class=tumblebounce spingt and ltdiv class=tumblegt

    The second version of toggleClass() uses the second parameter for determining whether theclass should be added or removed If this parameters value is t rue then the class is added iffalse the class is removed In essence the statement

    $(foo)toggleClass(className addOrRemove)

    is equivalent to

    i f (addOrRemove) $(foo)addClass(className) else $(foo)removeClass(className)

    As of jQuery 14 if no arguments are passed to toggleClass() all class names on the elementthe f irst t ime toggleClass() is called will be toggled Also as of jQuery 14 the class name to be

    toggled can be determined by passing in a funct ion

    $(divfoo)toggleClass(function() if ($(this)parent()is( bar)) return happy else return sad )

    This example will toggle the happy class for ltdiv class=foogt elements if their parent elementhas a class of bar otherwise it will toggle the sad class

    Example 1 Toggle the class highlight when a paragraph is clicked

    Javascript

    $(p)cl ick(function () $(this)toggleClass(highlight) )

    CSS

    p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundyellow

    HTML

    ltp class=bluegtClick to toggleltpgt ltp class=blue highlightgthighlightltpgt ltp class=bluegton theseltpgt ltp class=bluegtparagraphsltpgt

    Example 2 Add the highlight class to the clicked paragraph on every third click of thatparagraph remove it every f irst and second click

    Javascript

    var count = 0$(p)each(function() var $thisParagraph = $(this) var count = 0 $thisParagraphclick(function() count++ $thisParagraphfind(span)text(cl icks + count) $thisParagraphtoggleClass(highlight count 3 == 0) ))

    CSS

    p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundred

    HTML

    ltp class=bluegtClick to toggle (ltspangtclicks 0ltspangt)ltpgt ltp class=blue highlightgthighlight (ltspangtclicks 0ltspangt)ltpgt ltp class=bluegton these (ltspangtclicks 0ltspangt)ltpgt

    ltp class=bluegtparagraphs (ltspangtclicks 0ltspangt)ltpgt

    Example 3 Toggle the class name(s) indicated on the buttons for each div

    CSS

    wrap gt div float left width 100px margin 1em 1em 0 0 padding=left 3px border 1px solid abc diva background-color aqua divb background-color burlywood divc background-color cornsilk

    HTML

    ltdiv class=buttonsgt ltbuttongttoggleltbuttongt ltbutton class=agttoggle altbuttongt ltbutton class=a bgttoggle a bltbuttongt ltbutton class=a b cgttoggle a b cltbuttongt lta href=gtresetltagtltdivgtltdiv class=wrapgt ltdivgtltdivgt ltdiv class=bgtltdivgt ltdiv class=a bgtltdivgt ltdiv class=a cgtltdivgtltdivgt

    Javascript

    var cls = [ a a b a b c]var divs = $(divwrap)children()var appendClass = function() divsappend(function() return ltdivgt + (thisclassName || none) + ltdivgt )

    appendClass()

    $(button)bind(cl ick function() var tc = thisclassName || undefined divstoggleClass(tc) appendClass())

    $(a)bind(cl ick function(event) eventpreventDefault() divsempty()each(function(i) thisclassName = cls[i] ) appendClass())

    removeClass

    Remove a single class mult iple classes or all classes from each element in the set of matchedelements

    Added in version 14

    removeClass(funct ion(index class))jQuery

    funct ion(index A funct ion returning one or more space-separated class names to be

    class)Funct ion removed Receives the index posit ion of the element in the set and theold class value as arguments

    If a class name is included as a parameter then only that class will be removed from the set ofmatched elements If no class names are specif ied in the parameter all classes will be removed

    More than one class may be removed at a t ime separated by a space f rom the set of matchedelements like so

    $(p)removeClass(myClass yourClass)

    This method is of ten used with addClass() to switch elements classes from one to anotherlike so

    $(p)removeClass(myClass noClass)addClass(yourClass)

    Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

    To replace all exist ing classes with another class we can use at t r(class newClass) instead

    As of jQuery 14 the removeClass() method allows us to indicate the class to be removed bypassing in a funct ion

    $( l i last)removeClass(function() return $(this)prev()attr(class) )

    This example removes the class name of the penult imate ltligt f rom the last ltligt

    Example 1 Remove the class blue f rom the matched elements

    Javascript

    $(peven)removeClass(blue)

    CSS

    p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

    HTML

    ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

    ltp class=blue undergtGoodbyeltpgt

    Example 2 Remove the class blue and under f rom the matched elements

    Javascript

    $(podd)removeClass(blue under)

    CSS

    p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

    HTML

    ltp class=blue undergtHelloltpgt

    ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt ltp class=blue undergtGoodbyeltpgt

    Example 3 Remove all the classes from the matched elements

    Javascript

    $(peq(1))removeClass()

    CSS

    p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

    HTML

    ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

    ltp class=blue undergtGoodbyeltpgt

    hasClass

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

    Added in version 12

    hasClass(className)Boolean

    classNameString The class name to search for

    Elements may have more than one class assigned to them In HTML this is represented byseparat ing the class names with a space

    ltdiv id=mydiv class=foo bargtltdivgt

    The hasClass() method will return t rue if the class is assigned to an element even if otherclasses also are For example given the HTML above the following will return t rue

    $(mydiv)hasClass(foo)

    As would

    $(mydiv)hasClass(bar)

    While this would return false

    $(mydiv)hasClass(quux)

    Example 1 Looks for the paragraph that contains selected as a class

    Javascript

    $(divresult1)append($(pfirst)hasClass(selected)toString())$(divresult2)append($(plast)hasClass(selected)toString())$(divresult3)append($(p)hasClass(selected)toString())

    CSS

    p margin 8px font-size16px selected colorred

    HTML

    ltpgtThis paragraph is black and is the first paragraphltpgt ltp class=selectedgtThis paragraph is red and is the second paragraphltpgt

    ltdiv id=result1gtFirst paragraph has selected class ltdivgt ltdiv id=result2gtSecond paragraph has selected class ltdivgt ltdiv id=result3gtAt least one paragraph has selected class ltdivgt

    removeAttr

    Remove an at t ribute f rom each element in the set of matched elements

    Added in version 10

    removeAttr(at t ributeName)jQuery

    attributeNameString An at t ribute to remove

    The removeAttr() method uses the JavaScript removeAttribute() funct ion but it has theadvantage of being able to be called direct ly on a jQuery object and it accounts for dif ferentat t ribute naming across browsers

    NoteIf at tempt ing to remove an inline onclick event handler using removeAttr() one may f indthat this doesnt achieve the desired ef fect in Internet Explorer 67 or 8 Instead it isrecommended to opt for using prop() to achieve this as follows

    $elementprop(onclick null)consolelog(onclick property $element[0]onclick)

    We may update the behavior of removeAttr() at some point in the future to better handle thishowever for the t ime being the above should be considered the standard cross-browserapproach to this problem

    Example 1 Clicking the button enables the input next to it

    Javascript

    $(button)cl ick(function () $(this)next()removeAttr(disabled) focus() val(editable now))

    HTML

    ltbuttongtEnableltbuttongtltinput type=text disabled=disabled value=cant edit this gt

    attr

    Get the value of an at t ribute for the f irst element in the set of matched elements

    Added in version 10

    attr(at t ributeName)String

    attributeNameString The name of the at t ribute to get

    The at t r() method gets the at t ribute value for only the first element in the matched set To getthe value for each element individually use a looping construct such as jQuerys each() ormap() method

    As of jQuery 16 the at t r() method returns undef ined for at t ributes that have not been set Inaddit ion at t r() should not be used on plain objects arrays the window or the document Toretrieve and change DOM propert ies use the prop() method

    Using jQuerys at t r() method to get the value of an element s at t ribute has two main benef its

    1 Convenience It can be called direct ly on a jQuery object and chained to other jQuerymethods

    2 Cross-browser consistency The values of some attributes are reported inconsistent lyacross browsers and even across versions of a single browser The at t r() methodreduces such inconsistencies

    Note Attribute values are strings with the exception of a few attributes such asvalue and tabindex

    Example 1 Find the t it le at t ribute of the f irst in the page

    Javascript

    var title = $(em)attr(title) $(div)text(title)

    CSS

    em colorblue font-weightbold div colorred

    HTML

    ltpgt Once there was a ltem title=huge giganticgtlargeltemgt dinosaurltpgt

    The title of the emphasis isltdivgtltdivgt

    attr

    Set one or more at t ributes for the set of matched elements

    Added in version 11

    attr(at t ributeName funct ion(index at t r))jQuery

    attributeNameString The name of the at t ribute to set

    funct ion(indexat t r)Funct ion

    A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the oldattribute value as arguments

    The at t r() method is a convenient way to set the value of at t ributesacirceurordquoespecially when sett ingmult iple at t ributes or using values returned by a funct ion Consider the following image

    ltimg id=greatphoto src=brush-sellerjpg alt=brush seller gt

    Setting a simple attribute

    To change the alt at t ribute simply pass the name of the at t ribute and its new value to theat t r() method

    $(greatphoto)attr(alt Beij ing Brush Seller)

    Add an at t ribute the same way

    $(greatphoto)attr(title Photo by Kelly Clark)

    Setting several attributes at once

    To change the alt at t ribute and add the t it le at t ribute at the same t ime pass both sets ofnames and values into the method at once using a map (JavaScript object literal) Each key-value pair in the map adds or modif ies an at t ribute

    $(greatphoto)attr( alt Beij ing Brush Seller title photo by Kelly Clark)

    When sett ing mult iple at t ributes the quotes around at t ribute names are opt ional

    WARNING When sett ing the class at t ribute you must always use quotes

    Note jQuery prohibits changing the type at t ribute on an ltinputgt or ltbuttongt element and willthrow an error in all browsers This is because the type at t ribute cannot be changed in InternetExplorer

    Computed attribute values

    By using a funct ion to set at t ributes you can compute the value based on other propert ies ofthe element For example to concatenate a new value with an exist ing value

    $(greatphoto)attr(title function(i val) return val + - photo by Kelly Clark)

    This use of a funct ion to compute at t ribute values can be part icularly useful when modifyingthe at t ributes of mult iple elements at once

    Note If nothing is returned in the setter funct ion (ie funct ion(index at t r)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

    Example 1 Set some attributes for all s in the page

    Javascript

    $(img)attr( src imageshatgif title jQuery alt jQuery Logo)$(div)text($(img)attr(alt))

    CSS

    img padding10px div colorred font-size24px

    HTML

    ltimg gt ltimg gt ltimg gt

    ltdivgtltBgtAttribute of AjaxltBgtltdivgt

    Example 2 Disable buttons greater than the 1st button

    Javascript

    $(buttongt(1))attr(disableddisabled)

    CSS

    button margin10px

    HTML

    ltbuttongt0th Buttonltbuttongt ltbuttongt1st Buttonltbuttongt ltbuttongt2nd Buttonltbuttongt

    Example 3 Set the id for divs based on the posit ion in the page

    Javascript

    $(div)attr( id function (arr) return div-id + arr)each(function () $(span this)html((ID = ltbgt + thisid + ltbgt)))

    CSS

    div colorblue span colorred b font-weightbolder

    HTML

    ltdivgtZero-th ltspangtltspangtltdivgt ltdivgtFirst ltspangtltspangtltdivgt ltdivgtSecond ltspangtltspangtltdivgt

    Example 4 Set the src at t ribute f rom t it le at t ribute on the image

    Javascript

    $(img)attr(src function() return images + thistitle )

    HTML

    ltimg title=hatgifgt

    addClass

    Adds the specif ied class(es) to each of the set of matched elements

    Added in version 14

    addClass(funct ion(index currentClass))jQuery

    funct ion(indexcurrentClass)Funct ion

    A funct ion returning one or more space-separated class namesto be added to the exist ing class name(s) Receives the indexposit ion of the element in the set and the exist ing class name(s)as arguments Within the funct ion this refers to the currentelement in the set

    It s important to note that this method does not replace a class It simply adds the classappending it to any which may already be assigned to the elements

    More than one class may be added at a t ime separated by a space to the set of matchedelements like so

    $(p)addClass(myClass yourClass)

    This method is of ten used with removeClass() to switch elements classes from one toanother like so

    $(p)removeClass(myClass noClass)addClass(yourClass)

    Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

    As of jQuery 14 the addClass() methods argument can receive a funct ion

    $(ul l i last)addClass(function() return item- + $(this)index())

    Given an unordered list with f ive ltligt elements this example adds the class item-4 to the lastltligt

    Example 1 Adds the class selected to the matched elements

    Javascript

    $(plast)addClass(selected)

    CSS

    p margin 8px font-size16px selected colorblue highlight backgroundyellow

    HTML

    ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

    Example 2 Adds the classes selected and highlight to the matched elements

    Javascript

    $(plast)addClass(selected highlight)

    CSS

    p margin 8px font-size16px selected colorred highlight backgroundyellow

    HTML

    ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

    Example 3 Pass in a funct ion to addClass() to add the green class to a div that already has ared class

    Javascript

    $(div)addClass(function(index currentClass) var addedClass

    i f ( currentClass === red ) addedClass = green $(p)text(There is one green div) return addedClass )

    CSS

    div background white red background red redgreen background green

    HTML

    ltdivgtThis div should be whiteltdivgt ltdiv class=redgtThis div wil l be green because it now has the green and red classes It would be red if the addClass function failedltdivgt ltdivgtThis div should be whiteltdivgt ltpgtThere are zero green divsltpgt

    CSS

    jQuerycssHooks

    Hook direct ly into jQuery to override how part icular CSS propert ies are retrieved or set normalize CSS property naming or create custom propert ies

    Added in version 143

    The $cssHooks object provides a way to def ine funct ions for gett ing and sett ing part icularCSS values It can also be used to create new cssHooks for normalizing CSS3 features such asbox shadows and gradients

    For example some versions of Webkit -based browsers require -webkit -border-radius to set theborder-radius on an element while earlier Firefox versions require -moz-border-radius AcssHook can normalize these vendor-pref ixed propert ies to let css() accept a single standardproperty name (border-radius or with DOM property syntax borderRadius)

    In addit ion to providing f ine-grained control over how specif ic style propert ies are handled$cssHooks also extends the set of propert ies available to the animate() method

    Def ining a new cssHook is straight-forward The skeleton template below can serve as a guideto creat ing your own

    (function($) first check to see if cssHooks are supported if ( $cssHooks ) i f not output an error message throw(jQuery 143 or above is required for this plugin to work) return

    $cssHooks[someCSSProp] = get function( elem computed extra ) handle getting the CSS property set function( elem value ) handle setting the CSS value )(jQuery)

    Feature Testing

    Before normalizing a vendor-specif ic CSS property f irst determine whether the browsersupports the standard property or a vendor-pref ixed variat ion For example to check forsupport of the border-radius property see if any variat ion is a member of a temporary

    element s style object

    (function($) function styleSupport( prop ) var vendorProp supportedProp

    capitalize first character of the prop to test vendor prefix capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

    i f ( prop in divstyle )

    browser supports standard CSS property name supportedProp = prop else

    otherwise test support for vendor-prefixed property names for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

    avoid memory leak in IE div = null add property to $support so it can be accessed elsewhere $support[ prop ] = supportedProp return supportedProp

    call the function eg testing for border-radius support styleSupport( borderRadius ))(jQuery)

    Defining a complete cssHook

    To def ine a complete cssHook combine the support test with a f illed-out version of theskeleton template provided in the f irst example

    (function($) if ( $cssHooks ) throw(jQuery 143+ is needed for this plugin to work) return function styleSupport( prop ) var vendorProp supportedProp capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

    i f ( prop in divstyle ) supportedProp = prop else for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

    div = null $support[ prop ] = supportedProp return supportedProp

    var borderRadius = styleSupport( borderRadius )

    Set cssHooks only for browsers that support a vendor-prefixed border radius if ( borderRadius ampamp borderRadius == borderRadius ) $cssHookborderRadius = get function( elem computed extra ) return $css( elem borderRadius ) set function( elem value) elemstyle[ borderRadius ] = value )(jQuery)

    You can then set the border radius in a supported browser using either the DOM (camelCased)style or the CSS (hyphenated) style

    $(element)css(borderRadius 10px)$(another)css(border-radius 20px)

    If the browser lacks support for any form of the CSS property vendor-pref ixed or not the styleis not applied to the element However if the browser supports a proprietary alternat ive it canbe applied to the cssHooks instead

    (function($) feature test for support of a CSS property and a proprietary alternative

    i f ( $supportsomeCSSProp ampamp $supportsomeCSSProp == someCSSProp )

    Set cssHooks for browsers that support only a vendor-prefixed someCSSProp $cssHooksomeCSSProp = get function( elem computed extra ) return $css( elem $supportsomeCSSProp ) set function( elem value) elemstyle[ $supportsomeCSSProp ] = value else if ( supportsProprietaryAlternative ) $cssHooksomeCSSProp = get function( elem computed extra ) Handle crazy conversion from the proprietary alternative set function( elem value ) Handle crazy conversion to the proprietary alternative

    )(jQuery)

    Special units

    By default jQuery adds a px unit to the values passed to the css() method This behavior canbe prevented by adding the property to the jQuerycssNumber object

    $cssNumber[someCSSProp] = true

    Animating with cssHooks

    A cssHook can also hook into jQuerys animat ion mechanism by adding a property to thejQueryfxstep object

    $fxstep[someCSSProp] = function(fx) $cssHooks[someCSSProp]set( fxelem fxnow + fxunit )

    Note that this works best for simple numeric-value animat ions More custom code may berequired depending on the CSS property the type of value it returns and the animat ionscomplexity

    outerWidth

    Get the current computed width for the f irst element in the set of matched elements includingpadding and border

    Added in version 126

    outerWidth(includeMargin)Integer

    includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

    Returns the width of the element along with lef t and right padding border and opt ionallymargin in pixels

    If includeMargin is omit ted or false the padding and border are included in the calculat ion ift rue the margin is also included

    This method is not applicable to window and document objects for these use width() instead

    Example 1 Get the outerWidth of a paragraph

    Javascript

    var p = $(pfirst)$(plast)text( outerWidth + pouterWidth()+ outerWidth(true) + pouterWidth(true) )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    outerHeight

    Get the current computed height for the f irst element in the set of matched elements includingpadding border and opt ionally margin

    Added in version 126

    outerHeight(includeMargin)Integer

    includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

    The top and bottom padding and border are always included in the outerHeight() calculat ion ifthe includeMargin argument is set to t rue the margin (top and bottom) is also included

    This method is not applicable to window and document objects for these use height() instead

    Example 1 Get the outerHeight of aparagraph

    Javascript

    var p = $(pfirst)$(plast)text( outerHeight + pouterHeight() + outerHeight(true) + pouterHeight(true) )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    innerWidth

    Get the current computed width for the f irst element in the set of matched elements includingpadding but not border

    Added in version 126

    innerWidth()Integer

    This method returns the width of the element including lef t and right padding in pixels

    This method is not applicable to window and document objects for these use width() instead

    Example 1 Get the innerWidth of a paragraph

    Javascript

    var p = $(pfirst)$(plast)text( innerWidth + pinnerWidth() )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    innerHeight

    Get the current computed height for the f irst element in the set of matched elements includingpadding but not border

    Added in version 126

    innerHeight()Integer

    This method returns the height of the element including top and bottom padding in pixels

    This method is not applicable to window and document objects for these use height() instead

    Example 1 Get the innerHeight of aparagraph

    Javascript

    var p = $(pfirst)$(plast)text( innerHeight + pinnerHeight() )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    width

    Get the current computed width for the f irst element in the set of matched elements

    Added in version 10

    width()Integer

    The dif ference between css(width) and width() is that the lat ter returns a unit -less pixel value(for example 400) while the former returns a value with units intact (for example 400px) Thewidth() method is recommended when an element s width needs to be used in a mathematicalcalculat ion

    This method is also able to f ind the width of thewindow and document

    $(window)width() returns width of browser viewport$(document)width() returns width of HTML document

    Note that width() will always return the content width regardless of the value of the CSS box-sizing property

    Example 1 Show various widths Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

    Javascript

    function showWidth(ele w) $(div)text(The width for the + ele + is + w + px) $(getp)cl ick(function () showWidth(paragraph $(p)width()) ) $(getd)cl ick(function () showWidth(document $(document)width()) ) $(getw)cl ick(function () showWidth(window $(window)width()) )

    CSS

    body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

    HTML

    ltbutton id=getpgtGet Paragraph Widthltbuttongt ltbutton id=getdgtGet Document Widthltbuttongt ltbutton id=getwgtGet Window Widthltbuttongt

    ltdivgtampnbspltdivgt ltpgt Sample paragraph to test width ltpgt

    width

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

    Added in version 141

    width(funct ion(index width))jQuery

    funct ion(indexwidth)Funct ion

    A funct ion returning the width to set Receives the index posit ion ofthe element in the set and the old width as arguments Within thefunct ion this refers to the current element in the set

    When calling width(value) the value can be either a string (number and unit ) or a number Ifonly 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 100px 50 or auto)Note that in modern browsers the CSS width property does not include padding border ormargin unless the box-sizing CSS property is used

    If no explicit unit was specif ied (like em or ) then px is concatenated to the value

    Note that width(value) sets the width of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterWidth of the box instead of the content width

    Example 1 To set the width of each div on click to 30px plus a color change

    Javascript

    $(div)one(cl ick function () $(this)width(30) css(cursorauto background-colorblue) )

    CSS

    div width70px height50px floatleft margin5px backgroundred cursorpointer

    HTML

    ltdivgtltdivgt ltdivgtdltdivgt

    ltdivgtdltdivgt ltdivgtdltdivgt ltdivgtdltdivgt

    height

    Get the current computed height for the f irst element in the set of matched elements

    Added in version 10

    height()Integer

    The dif ference between css(height ) and height() is that the lat ter returns a unit -less pixelvalue (for example 400) while the former returns a value with units intact (for example 400px)The height() method is recommended when an element s height needs to be used in amathematical calculat ion

    This method is also able to f ind the heightof the window and document

    $(window)height() returns height of browser viewport$(document)height() returns height of HTML document

    Note that height() will always return the content height regardless of the value of the CSSbox-sizing property

    Example 1 Show various heights Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

    Javascript

    function showHeight(ele h) $(div)text(The height for the + ele + is + h + px) $(getp)cl ick(function () showHeight(paragraph $(p)height()) ) $(getd)cl ick(function () showHeight(document $(document)height()) ) $(getw)cl ick(function () showHeight(window $(window)height()) )

    CSS

    body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

    HTML

    ltbutton id=getpgtGet Paragraph Heightltbuttongt ltbutton id=getdgtGet Document Heightltbuttongt ltbutton id=getwgtGet Window Heightltbuttongt

    ltdivgtampnbspltdivgt ltpgt Sample paragraph to test height ltpgt

    height

    Set the CSS height of every matched element

    Added in version 141

    height(funct ion(index height))jQuery

    funct ion(indexheight)Funct ion

    A funct ion returning the height to set Receives the index posit ion ofthe element in the set and the old height as arguments Within thefunct ion this refers to the current element in the set

    When calling height(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is providedhowever a valid CSS measurement must be provided for the height (such as 100px 50 orauto) Note that in modern browsers the CSS height property does not include paddingborder or margin

    If no explicit unit was specif ied (like em or ) then px is concatenated to the value

    Note that height(value) sets the height of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterHeight of the box instead of the content height

    Example 1 To set the height of each div on click to 30px plus a color change

    Javascript

    $(div)one(cl ick function () $(this)height(30) css(cursorauto backgroundColorgreen) )

    CSS

    div width50px height70px floatleft margin5px backgroundrgb(2551400) cursorpointer

    HTML

    ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    scrollLeft

    Get the current horizontal posit ion of the scroll bar for the f irst element in the set of matchedelements

    Added in version 126

    scrollLef t ()Integer

    The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area If the scroll bar is at the very lef t or if the element is not scrollablethis number will be 0

    Example 1 Get the scrollLef t of a paragraph

    Javascript

    var p = $(pfirst) $(plast)text( scrollLeft + pscrollLeft() )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    scrollLeft

    Set the current horizontal posit ion of the scroll bar for each of the set of matched elements

    Added in version 126

    scrollLef t (value)jQuery

    valueNumber An integer indicat ing the new posit ion to set the scroll bar to

    The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area Sett ing the scrollLef t posit ions the horizontal scroll of each matchedelement

    Example 1 Set the scrollLef t of a div

    Javascript

    $(divdemo)scrollLeft(300)

    CSS

    divdemo backgroundCCCCCC none repeat scroll 0 0 border3px solid 666666 margin5px padding5px positionrelative width200px height100px overflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

    HTML

    ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

    scrollTop

    Get the current vert ical posit ion of the scroll bar for the f irst element in the set of matchedelements

    Added in version 126

    scrollTop()Integer

    The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area If the scroll bar is at the very top or if the element is not scrollable thisnumber will be 0

    Example 1 Get the scrollTop of a paragraph

    Javascript

    var p = $(pfirst)$(plast)text( scrollTop + pscrollTop() )

    CSS

    p margin10pxpadding5pxborder2px solid 666

    HTML

    ltpgtHelloltpgtltpgtltpgt

    scrollTop

    Set the current vert ical posit ion of the scroll bar for each of the set of matched elements

    Added in version 126

    scrollTop(value)jQuery

    valueNumber An integer indicat ing the new posit ion to set the scroll bar to

    The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area Sett ing the scrollTop posit ions the vert ical scroll of each matched element

    Example 1 Set the scrollTop of a div

    Javascript

    $(divdemo)scrollTop(300)

    CSS

    divdemo backgroundCCCCCC none repeat scroll 0 0border3px solid 666666margin5pxpadding5pxpositionrelativewidth200pxheight100pxoverflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

    HTML

    ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

    position

    Get the current coordinates of the f irst element in the set of matched elements relat ive to theoffset parent

    Added in version 12

    posit ion()Object

    The posit ion() method allows us to retrieve the current posit ion of an element relative to theoffset parent Contrast this with of fset() which retrieves the current posit ion relative to thedocument When posit ioning a new element near another one and within the same containingDOM element posit ion() is the more useful

    Returns an object containing the propert ies top and lef t

    Example 1 Access the posit ion of the second paragraph

    Javascript

    var p = $(pfirst)var position = pposition()$(plast)text( left + positionleft + top + positiontop )

    CSS

    div padding 15px p margin-left10px

    HTML

    ltdivgt ltpgtHelloltpgtltdivgtltpgtltpgt

    offset

    Get the current coordinates of the f irst element in the set of matched elements relat ive to thedocument

    Added in version 12

    offset()Object

    The of fset() method allows us to retrieve the current posit ion of an element relative to thedocument Contrast this with posit ion() which retrieves the current posit ion relative to the offsetparent When posit ioning a new element on top of an exist ing one for global manipulat ion (inpart icular for implement ing drag-and-drop) of fset() is the more useful

    of fset() returns an object containing the propert ies top and lef t

    Note jQuery does not support getting the offset coordinates of hidden elements oraccounting for borders margins or padding set on the body element

    Example 1 Access the of fset of the second paragraph

    Javascript

    var p = $(plast)var offset = poffset()phtml( left + offsetleft + top + offsettop )

    CSS

    p margin-left10px

    HTML

    ltpgtHelloltpgtltpgt2nd Paragraphltpgt

    Example 2 Click to see the of fset

    Javascript

    $( documentbody)cl ick(function (e) var offset = $(this)offset() estopPropagation() $(result)text(thistagName + coords ( + offsetleft + + offsettop + )))

    CSS

    p margin-left10px colorblue width200px cursorpointer span colorred cursorpointer divabs width50px height50px positionabsolute left220px top35px background-colorgreen cursorpointer

    HTML

    ltdiv id=resultgtClick an elementltdivgtltpgt This is the best way to ltspangtfindltspangt an offsetltpgt

    ltdiv class=absgtltdivgt

    offset

    Set the current coordinates of every element in the set of matched elements relat ive to thedocument

    Added in version 14

    offset(funct ion(index coords))jQuery

    funct ion(indexcoords)Funct ion

    A funct ion to return the coordinates to set Receives the index of theelement in the collect ion as the f irst argument and the currentcoordinates as the second argument The funct ion should return anobject with the new top and lef t propert ies

    The of fset() set ter method allows us to reposit ion an element The element s posit ion isspecif ied relative to the document If the element s posit ion style property is current ly stat ic it

    will be set to relat ive to allow for this reposit ioning

    Example 1 Set the of fset of the second paragraph

    Javascript

    $(plast)offset( top 10 left 30 )

    CSS

    p margin-left10px

    HTML

    ltpgtHelloltpgtltpgt2nd Paragraphltpgt

    css

    Get the value of a style property for the f irst element in the set of matched elements

    Added in version 10

    css(propertyName)String

    propertyNameString A CSS property

    The css() method is a convenient way to get a style property f rom the f irst matched elementespecially in light of the dif ferent ways browsers access most of those propert ies (thegetComputedStyle() method in standards-based browsers versus the currentStyle andrunt imeStyle propert ies in Internet Explorer) and the dif ferent terms browsers use for certainpropert ies For example Internet Explorers DOM implementat ion refers to the f loat property asstyleFloat while W3C standards-compliant browsers refer to it as cssFloat The css() methodaccounts for such dif ferences producing the same result no matter which term we use Forexample an element that is f loated lef t will return the string lef t for each of the following threelines

    1 $(divlef t )css(f loat )

    2 $(divlef t )css(cssFloat )

    3 $(divlef t )css(styleFloat )

    Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color)and css(backgroundColor) Dif ferent browsers may return CSS color values that are logicallybut not textually equal eg FFF f f f f f f and rgb(255255255)

    but not textually equal eg FFF f f f f f f and rgb(255255255)

    Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

    Example 1 To access the background color of a clicked div

    Javascript

    $(div)cl ick(function () var color = $(this)css(background-color) $(result)html(That div is ltspan style=color + color + gt + color + ltspangt))

    CSS

    div width60px height60px margin5px floatleft

    HTML

    ltspan id=resultgtampnbspltspangtltdiv style=background-colorbluegtltdivgtltdiv style=background-colorrgb(159930)gtltdivgt

    ltdiv style=background-color123456gtltdivgtltdiv style=background-colorf11gtltdivgt

    css

    Set one or more CSS propert ies for the set of matched elements

    Added in version 10

    css(map)jQuery

    mapMap A map of property-value pairs to set

    As with the prop() method the css() method makes sett ing propert ies of elements quick andeasy This method can take either a property name and value as separate parameters or asingle map of key-value pairs (JavaScript object notat ion)

    Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color

    f fe border-lef t 5px solid ccc) and css(backgroundColor f fe borderLeft 5px solidccc) Not ice that with the DOM notat ion quotat ion marks around the property names areopt ional but with CSS notat ion theyre required due to the hyphen in the name

    When using css() as a setter jQuery modif ies the element s style property For example$(mydiv)css(color green) is equivalent to documentgetElementById(mydiv)stylecolor =green Sett ing the value of a style property to an empty string acirceurordquo eg $(mydiv)css(color )acirceurordquo removes that property f rom an element if it has already been direct ly applied whether in theHTML style at t ribute through jQuerys css() method or through direct DOM manipulat ion ofthe style property It does not however remove a style that has been applied with a CSS rule ina stylesheet or ltstylegt element

    As of jQuery 16 css() accepts relat ive values similar to animate() Relat ive values are a stringstart ing with += or -= to increment or decrement the current value For example if an element spadding-lef t was 10px css( padding-lef t +=15 ) would result in a total padding-lef t of 25px

    As of jQuery 14 css() allows us to pass a funct ion as the property value

    $(divexample)css(width function(index) return index 50)

    This example sets the widths of the matched elements to incrementally larger values

    Note If nothing is returned in the setter funct ion (ie funct ion(index style)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

    Example 1 To change the color of any paragraph to red on mouseover event

    Javascript

    $(p)mouseover(function () $(this)css(colorred) )

    CSS

    p colorblue width200px font-size14px

    HTML

    ltpgtJust roll the mouse over meltpgt

    ltpgtOr me to see a color changeltpgt

    Example 2 Increase the width of box by 200 pixels

    Javascript

    $(box)one( cl ick function () $( this )css( width+=200 ) )

    CSS

    box background black color snow width100px padding10px

    HTML

    ltdiv id=boxgtClick me to growltdivgt

    Example 3 To highlight a clicked word in the paragraph

    Javascript

    var words = $(pfirst)text()split( ) var text = wordsjoin(ltspangt ltspangt) $(pfirst)html(ltspangt + text + ltspangt) $(span)cl ick(function () $(this)css(background-coloryellow) )

    CSS

    p colorblue font-weightbold cursorpointer

    HTML

    ltpgt Once upon a time there was a man who l ived in a pizza parlor This man just loved pizza and ate it al l the time He went on to be the happiest man in the world The endltpgt

    Example 4 To set the color of all paragraphs to red and background to blue

    Javascript

    $(p)hover(function () $(this)css(background-color yellow font-weight bolder) function () var cssObj = background-color ddd font-weight color rgb(040244) $(this)css(cssObj) )

    CSS

    p colorgreen

    HTML

    ltpgtMove the mouse over a paragraphltpgt ltpgtLike this one or the one aboveltpgt

    Example 5 Increase the size of a div when you click it

    Javascript

    $(div)cl ick(function() $(this)css( width function(index value) return parseFloat(value) 12 height function(index value) return parseFloat(value) 12

    ) )

    CSS

    div width 20px height 15px background-color f33

    HTML

    ltdivgtclickltdivgt ltdivgtclickltdivgt

    toggleClass see Attributes

    removeClass see Attributes

    hasClass see Attributes

    addClass see Attributes

    Manipulation

    removeProp see Attributes

    prop see Attributes

    prop see Attributes

    outerWidth see CSS

    outerHeight see CSS

    innerWidth see CSS

    innerHeight see CSS

    width see CSS

    width see CSS

    height see CSS

    height see CSS

    scrollLeft see CSS

    scrollLeft see CSS

    scrollTop see CSS

    scrollTop see CSS

    position see CSS

    offset see CSS

    offset see CSS

    css see CSS

    css see CSS

    unwrap

    Remove the parents of the set of matched elements f rom the DOM leaving the matchedelements in their place

    Added in version 14

    unwrap()jQuery

    The unwrap() method removes the element s parent This is ef fect ively the inverse of thewrap() method The matched elements (and their siblings if any) replace their parents withinthe DOM structure

    Example 1 Wrapunwrap a div around each of the paragraphs

    Javascript

    $(button)toggle(function() $(p)wrap(ltdivgtltdivgt) function() $(p)unwrap())

    CSS

    div border 2px solid blue p backgroundyellow margin4px

    HTML

    ltbuttongtwrapunwrapltbuttongtltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

    detach

    Remove the set of matched elements f rom the DOM

    Added in version 14

    detach(selector)jQuery

    selectorSelector (opt ional) A selector expression that f ilters the set of matchedelements to be removed

    The detach() method is the same as remove() except that detach() keeps all jQuery dataassociated with the removed elements This method is useful when removed elements are tobe reinserted into the DOM at a later t ime

    Example 1 Detach all paragraphs from the DOM

    Javascript

    $(p)cl ick(function() $(this)toggleClass(off) ) var p $(button)cl ick(function() i f ( p ) pappendTo(body) p = null else p = $(p)detach() )

    CSS

    p backgroundyellow margin6px 0 poff background black

    HTML

    ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtAttachdetach paragraphsltbuttongt

    clone

    Create a deep copy of the set of matched elements

    Added in version 15

    clone(withDataAndEvents deepWithDataAndEvents)jQuery

    withDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data should be copied along with the

    elements The default value is false In jQuery 150the default value was incorrectly true it was changedback to false in 151 and up

    deepWithDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data for all children of the clonedelement should be copied By default its valuematches the f irst argument s value (which defaultsto false)

    The clone() method performs a deep copy of the set of matched elements meaning that itcopies the matched elements as well as all of their descendant elements and text nodes Whenused in conjunct ion with one of the insert ion methods clone() is a convenient way to duplicateelements on a page Consider the following HTML

    ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    As shown in the discussion for append() normally when an element is inserted somewhere inthe DOM it is moved from its old locat ion So given the code

    $(hello)appendTo(goodbye)

    The result ing DOM structure would be

    ltdiv class=containergt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

    To prevent this and instead create a copy of the element you could write the following

    $(hello)clone()appendTo(goodbye)

    This would produce

    ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

    Note that when using the clone() method you can modify the cloned elements ortheir contents before (re-)inserting them into the document

    Normally any event handlers bound to the original element are not copied to the clone Theopt ional withDataAndEvents parameter allows us to change this behavior and to instead makecopies of all of the event handlers as well bound to the new copy of the element As of jQuery14 all element data (at tached by the data() method) is also copied to the new copy

    However objects and arrays within element data are not copied and will cont inue to be sharedbetween the cloned element and the original element To deep copy all data copy each onemanually

    var $elem = $(elem)data( arr [ 1 ] ) Original element with attached data $clone = $elemclone( true ) data( arr $extend( [] $elemdata(arr) ) ) Deep copy to prevent data sharing

    As of jQuery 15 withDataAndEvents can be opt ionally enhanced withdeepWithDataAndEvents to copy the events and data for all children of the cloned element

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

    Javascript

    $(b)clone()prependTo(p)

    HTML

    ltbgtHelloltbgtltpgt how are youltpgt

    Example 2 When using clone() to clone a collect ion of elements that are not at tached to theDOM their order when inserted into the DOM is not guaranteed However it may be possible topreserve sort order with a workaround as demonstrated

    CSS

    orig copy copy-correct float left width 20

    Javascript

    sort order is not guaranteed here and may vary with browser $(copy)append($(orig elem) clone() children(a) prepend(foo - ) parent() clone()) correct way to approach where order is maintained$(copy-correct) append($(orig elem) clone() children(a) prepend(bar - ) end())

    HTML

    ltdiv id=origgt ltdiv class=elemgtltagt1ltagtltdivgt ltdiv class=elemgtltagt2ltagtltdivgt ltdiv class=elemgtltagt3ltagtltdivgt ltdiv class=elemgtltagt4ltagtltdivgt ltdiv class=elemgtltagt5ltagtltdivgtltdivgtltdiv id=copygtltdivgtltdiv id=copy-correctgtltdivgt

    remove

    Remove the set of matched elements f rom the DOM

    Added in version 10

    remove(selector)jQuery

    selectorString (opt ional) A selector expression that f ilters the set of matchedelements to be removed

    Similar to empty() the remove() method takes elements out of the DOM Use remove() when

    you want to remove the element itself as well as everything inside it In addit ion to theelements themselves all bound events and jQuery data associated with the elements areremoved To remove the elements without removing data and events use detach() instead

    Consider the following HTML

    ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    We can target any element for removal

    $(hello)remove()

    This will result in a DOM structure with the ltdivgt element deleted

    ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo Other jQuery constructs such as data or event handlers are erased as well

    We can also include a selector as an opt ional parameter For example we could rewrite theprevious DOM removal code as follows

    $(div)remove(hello)

    This would result in the same DOM structure

    ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    Example 1 Removes all paragraphs from the DOM

    Javascript

    $(button)cl ick(function () $(p)remove() )

    CSS

    p backgroundyellow margin6px 0

    HTML

    ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtCall remove() on paragraphsltbuttongt

    Example 2 Removes all paragraphs that contain Hello f rom the DOM Analogous to doing$(p)f ilter(contains(Hello))remove()

    Javascript

    $(button)cl ick(function () $(p)remove(contains(Hello)) )

    CSS

    p backgroundyellow margin6px 0

    HTML

    ltp class=hellogtHelloltpgt how are ltpgtyoultpgt

    ltbuttongtCall remove(contains(Hello)) on paragraphsltbuttongt

    empty

    Remove all child nodes of the set of matched elements f rom the DOM

    Added in version 10

    empty()jQuery

    This method removes not only child (and other descendant) elements but also any text withinthe set of matched elements This is because according to the DOM specif icat ion any stringof text within an element is considered a child node of that element Consider the followingHTML

    ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    We can target any element for removal

    $(hello)empty()

    This will result in a DOM structure with the Hello text deleted

    ltdiv class=containergt ltdiv class=hellogtltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

    If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo

    To avoid memory leaks jQuery removes other constructs such as data and event handlersfrom the child elements before removing the elements themselves

    Example 1 Removes all child nodes (including text nodes) f rom all paragraphs

    Javascript

    $(button)cl ick(function () $(p)empty() )

    CSS

    p backgroundyellow

    HTML

    ltpgt Hello ltspangtPersonltspangt lta href=javascriptgtand personltagtltpgt

    ltbuttongtCall empty() on above paragraphltbuttongt

    replaceAll

    Replace each target element with the set of matched elements

    Added in version 12

    replaceAll(target)jQuery

    targetSelector A selector expression indicat ing which element(s) to replace

    The replaceAll() method is corollary to replaceWith() but with the source and target reversedConsider this DOM structure

    ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

    We can create an element then replace other elements with it

    $(lth2gtNew headinglth2gt)replaceAll( inner)

    This causes all of them to be replaced

    ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

    Or we could select an element to use as the replacement

    $(first)replaceAll( third)

    This results in the DOM structure

    ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

    From this example we can see that the selected element replaces the target by being movedfrom its old locat ion not by being cloned

    Example 1 Replace all the paragraphs with bold words

    Javascript

    $(ltbgtParagraph ltbgt)replaceAll(p) check replaceWith() examples

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    replaceWith

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

    Added in version 14

    replaceWith(funct ion)jQuery

    funct ionFunct ion A funct ion that returns content with which to replace the set ofmatched elements

    The replaceWith() method removes content f rom the DOM and inserts new content in its placewith a single call Consider this DOM structure

    ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

    The second inner ltdivgt could be replaced with the specif ied HTML

    $(divsecond)replaceWith(lth2gtNew headinglth2gt)

    This results in the structure

    ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt lth2gtNew headinglth2gt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

    All inner ltdivgt elements could be targeted at once

    $(divinner)replaceWith(lth2gtNew headinglth2gt)

    This causes all of them to be replaced

    ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

    An element could also be selected as the replacement

    $(divthird)replaceWith($(first))

    This results in the DOM structure

    ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

    This example demonstrates that the selected element replaces the target by being moved fromits old locat ion not by being cloned

    The replaceWith() method like most jQuery methods returns the jQuery object so that othermethods can be chained onto it However it must be noted that the original jQuery object isreturned This object refers to the element that has been removed from the DOM not the newelement that has replaced it

    As of jQuery 14 replaceWith() can also work on disconnected DOM nodes For example withthe following code replaceWith() returns a jQuery set containing only a paragraph

    $(ltdivgt)replaceWith(ltpgtltpgt)

    The replaceWith() method can also take a funct ion as its argument

    $(divcontainer)replaceWith(function() return $(this)contents())

    This results in ltdiv class=containergt being replaced by its three child ltdivgts The return valueof the funct ion may be an HTML string DOM element or jQuery object

    Example 1 On click replace the button with a div containing the same word

    Javascript

    $(button)cl ick(function () $(this)replaceWith( ltdivgt + $(this)text() + ltdivgt ))

    CSS

    button displayblock margin3px colorred width200px div colorred border2px solid blue width200px margin3px text-aligncenter

    HTML

    ltbuttongtFirstltbuttongtltbuttongtSecondltbuttongtltbuttongtThirdltbuttongt

    Example 2 Replace all paragraphs with bold words

    Javascript

    $(p)replaceWith( ltbgtParagraph ltbgt )

    HTML

    ltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

    Example 3 On click replace each paragraph with a div that is already in the DOM and selectedwith the $() funct ion Not ice it doesnt clone the object but rather moves it to replace theparagraph

    Javascript

    $(p)cl ick(function () $(this)replaceWith( $(div) ))

    CSS

    div border2px solid blue colorred margin3px p border2px solid red colorblue margin3px cursorpointer

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    ltdivgtReplacedltdivgt

    Example 4 On button click replace the containing div with its child divs and append the classname of the selected element to the paragraph

    Javascript

    $(button)bind(click function() var $container = $(divcontainer)replaceWith(function() return $(this)contents() )

    $(p)append( $containerattr(class) ))

    CSS

    container background-color 991 inner color 911

    HTML

    ltpgt ltbuttongtReplaceltbuttongtltpgtltdiv class=containergt ltdiv class=innergtScoobyltdivgt ltdiv class=innergtDoobyltdivgt ltdiv class=innergtDooltdivgtltdivgt

    wrapInner

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

    Added in version 14

    wrapInner(funct ion(index))jQuery

    funct ion(index)Funct ion A callback funct ion which generates a structure to wraparound the content of the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

    The wrapInner() funct ion can take any string or object that could be passed to the $() factoryfunct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element The structure will be wrapped around the content ofeach of the elements in the set of matched elements

    Consider the following HTML

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    Using wrapInner() we can insert an HTML structure around the content of each inner ltdivgtelements like so

    $(inner)wrapInner(ltdiv class=new gt)

    The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around the content of each matched element

    ltdiv class=containergt ltdiv class=innergt ltdiv class=newgtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=newgtGoodbyeltdivgt ltdivgtltdivgt

    The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the content of the correspondingelement For example

    $(inner)wrapInner(function() return ltdiv class= + thisnodeValue + gt)

    This will cause each ltdivgt to have a class corresponding to the text it wraps

    ltdiv class=containergt ltdiv class=innergt ltdiv class=HellogtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=GoodbyegtGoodbyeltdivgt ltdivgtltdivgt

    Note When passing a selector string to the wrapInner() funct ion the expected input is wellformed HTML with correct ly closed tags Examples of valid input include

    $(elem)wrapInner(ltdiv class=test gt)$(elem)wrapInner(ltdiv class=testgtltdivgt)$(elem)wrapInner(ltdiv class=testgtltdivgt)

    Example 1 Selects all paragraphs and wraps a bold tag around each of its contents

    Javascript

    $(p)wrapInner(ltbgtltbgt)

    CSS

    p backgroundbbf

    HTML

    ltpgtHelloltpgt

    ltpgtcruelltpgt ltpgtWorldltpgt

    Example 2 Wraps a newly created tree of objects around the inside of the body

    Javascript

    $(body)wrapInner(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

    CSS

    div border2px green solid margin2px padding2px p backgroundyellow margin2px padding2px

    HTML

    Plain old text or is it

    Example 3 Selects all paragraphs and wraps a bold tag around each of its contents

    Javascript

    $(p)wrapInner(documentcreateElement(b))

    CSS

    p background9f9

    HTML

    ltpgtHelloltpgt

    ltpgtcruelltpgt ltpgtWorldltpgt

    Example 4 Selects all paragraphs and wraps a jQuery object around each of its contents

    Javascript

    $(p)wrapInner($(ltspan class=redgtltspangt))

    CSS

    p background9f9 red colorred

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    wrapAll

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

    Added in version 12

    wrapAll(wrappingElement)jQuery

    wrappingElementStringSelector ElementjQuery

    An HTML snippet selector expression jQuery object or DOMelement specifying the structure to wrap around the matchedelements

    The wrapAll() funct ion can take any string or object that could be passed to the $() funct ion tospecify a DOM structure This structure may be nested several levels deep but should containonly one inmost element The structure will be wrapped around all of the elements in the set ofmatched elements as a single group

    Consider the following HTML

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    Using wrapAll() we can insert an HTML structure around the inner ltdivgt elements like so

    $(inner)wrapAll(ltdiv class=new gt)

    The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around all matched elements

    ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

    Example 1 Wrap a new div around all of the paragraphs

    Javascript

    $(p)wrapAll(ltdivgtltdivgt)

    CSS

    div border 2px solid blue p backgroundyellow margin4px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

    Javascript

    $(span)wrapAll(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

    CSS

    div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

    HTML

    ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

    Example 3 Wrap a new div around all of the paragraphs

    Javascript

    $(p)wrapAll(documentcreateElement(div))

    CSS

    div border 2px solid blue p backgroundyellow margin4px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

    Javascript

    $(p)wrapAll($(doublediv))

    CSS

    div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

    wrap

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

    Added in version 14

    wrap(funct ion(index))jQuery

    funct ion(index)Funct ion A callback funct ion returning the HTML content or jQueryobject to wrap around the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

    The wrap() funct ion can take any string or object that could be passed to the $() factory

    funct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element A copy of this structure will be wrapped around eachof the elements in the set of matched elements This method returns the original set ofelements for chaining purposes

    Consider the following HTML

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    Using wrap() we can insert an HTML structure around the inner ltdivgt elements like so

    $(inner)wrap(ltdiv class=new gt)

    The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around each matched element

    ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=newgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

    The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the corresponding element Forexample

    $(inner)wrap(function() return ltdiv class= + $(this)text() + gt)

    This will cause each ltdivgt to have a class corresponding to the text it wraps

    ltdiv class=containergt ltdiv class=Hellogt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=Goodbyegt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

    Example 1 Wrap a new div around all of the paragraphs

    Javascript

    $(p)wrap(ltdivgtltdivgt)

    CSS

    div border 2px solid blue p backgroundyellow margin4px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

    Javascript

    $(span)wrap(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

    CSS

    div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

    HTML

    ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

    Example 3 Wrap a new div around all of the paragraphs

    Javascript

    $(p)wrap(documentcreateElement(div))

    CSS

    div border 2px solid blue p backgroundyellow margin4px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

    Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

    Javascript

    $(p)wrap($(doublediv))

    CSS

    div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

    HTML

    ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

    insertBefore

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

    Added in version 10

    insertBefore(target)jQuery

    targetSelectorElementjQuery

    A selector element HTML string or jQuery object the matched set ofelements will be inserted before the element(s) specif ied by thisparameter

    The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

    Consider the following HTML

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    We can create content and insert it before several elements at once

    $(ltpgtTestltpgt)insertBefore(inner)

    Each inner ltdivgt element gets this new content

    ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Example 1 Inserts all paragraphs before an element with id of foo Same as$( foo)before(p)

    Javascript

    $(p)insertBefore(foo) check before() examples

    CSS

    foo backgroundyellow

    HTML

    ltdiv id=foogtFOOltdivgtltpgtI would l ike to say ltpgt

    before

    Insert content specif ied by the parameter before each element in the set of matchedelements

    Added in version 14

    before(funct ion)jQuery

    funct ionFunct ion A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert before each element in the set of matched elementsReceives the index posit ion of the element in the set as anargument Within the funct ion this refers to the current element inthe set

    The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

    Consider the following HTML

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    You can create content and insert it before several elements at once

    $(inner)before(ltpgtTestltpgt)

    Each inner ltdivgt element gets this new content

    ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    In jQuery 14 before() and af ter() will also work on disconnected DOM nodes

    $(ltdivgt)before(ltpgtltpgt)

    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 prepend() and af ter() before() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

    For example the following will insert two new ltdivgts and an exist ing ltdivgt before the f irstparagraph

    var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

    $(p)first()before($newdiv1 [newdiv2 existingdiv1])

    Since before() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so$(p)f irst()before($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

    Example 1 Inserts some HTML before all paragraphs

    Javascript

    $(p)before(ltbgtHelloltbgt)

    CSS

    p backgroundyellow

    HTML

    ltpgt is what I saidltpgt

    Example 2 Inserts a DOM element before all paragraphs

    Javascript

    $(p)before( documentcreateTextNode(Hello) )

    CSS

    p backgroundyellow

    HTML

    ltpgt is what I saidltpgt

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

    Javascript

    $(p)before( $(b) )

    CSS

    p backgroundyellow

    HTML

    ltpgt is what I saidltpgtltbgtHelloltbgt

    insertAfter

    Insert every element in the set of matched elements af ter the target

    Added in version 10

    insertAfter(target)jQuery

    targetSelectorElementjQuery

    A selector element HTML string or jQuery object the matched set ofelements will be inserted af ter the element(s) specif ied by thisparameter

    The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

    Consider the following HTML

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    We can create content and insert it af ter several elements at once

    $(ltpgtTestltpgt)insertAfter( inner)

    Each inner ltdivgt element gets this new content

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

    We can also select an element on the page and insert it af ter another

    $(h2)insertAfter($(container))

    If an element selected this way is inserted elsewhere it will be moved af ter the target (notcloned)

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Example 1 Inserts all paragraphs af ter an element with id of foo Same as $( foo)af ter(p)

    Javascript

    $(p)insertAfter(foo) check after() examples

    CSS

    foo backgroundyellow

    HTML

    ltpgt is what I said ltpgtltdiv id=foogtFOOltdivgt

    after

    Insert content specif ied by the parameter af ter each element in the set of matched elements

    Added in version 14

    after(funct ion(index))jQuery

    funct ion(index)Funct ion A funct ion that returns an HTML string DOM element(s) orjQuery object to insert af ter each element in the set ofmatched elements Receives the index posit ion of theelement in the set as an argument Within the funct ion thisrefers to the current element in the set

    The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

    Using the following HTML

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    Content can be created and then inserted af ter several elements at once

    $(inner)after(ltpgtTestltpgt)

    Each inner ltdivgt element gets this new content

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

    An element in the DOM can also be selected and inserted af ter another element

    $(container)after($(h2))

    If an element selected this way is inserted elsewhere it will be moved rather than cloned

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Inserting Disconnected DOM nodes

    As of jQuery 14 before() and af ter() will also work on disconnected DOM nodes For examplegiven the following code

    $(ltdivgt)after(ltpgtltpgt)

    The result is a jQuery set containing a div and a paragraph in that order That set can befurther manipulated even before it is inserted in the document

    $(ltdivgt)after(ltpgtltpgt)addClass(foo) fi lter(p)attr( id bar)html(hello)end()appendTo(body)

    This results in the following elements inserted just before the closing ltbodygt tag

    ltdiv class=foogtltdivgtltp class=foo id=bargthelloltpgt

    Passing a Function

    As of jQuery 14 af ter() supports passing a funct ion that returns the elements to insert

    $(p)after(function() return ltdivgt + thisclassName + ltdivgt)

    This example inserts a ltdivgt af ter each paragraph with each new ltdivgt containing the class

    name(s) of its preceding paragraph

    Additional Arguments

    Similar to other content-adding methods such as prepend() and before() af ter() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

    For example the following will insert two new ltdivgts and an exist ing ltdivgt af ter the f irstparagraph

    var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

    $(p)first()after($newdiv1 [newdiv2 existingdiv1])

    Since af ter() can accept any number of addit ional arguments the same result can be achievedby passing in the three ltdivgts as three separate arguments like so $(p)f irst()af ter($newdiv1newdiv2 exist ingdiv1) The type and number of arguments will largely depend on the elementsare collected in the code

    Example 1 Inserts some HTML after all paragraphs

    Javascript

    $(p)after(ltbgtHelloltbgt)

    CSS

    p backgroundyellow

    HTML

    ltpgtI would l ike to say ltpgt

    Example 2 Inserts a DOM element af ter all paragraphs

    Javascript

    $(p)after( documentcreateTextNode(Hello) )

    CSS

    p backgroundyellow

    HTML

    ltpgtI would l ike to say ltpgt

    Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) af ter all paragraphs

    Javascript

    $(p)after( $(b) )

    CSS

    p backgroundyellow

    HTML

    ltbgtHelloltbgtltpgtI would l ike to say ltpgt

    prependTo

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

    Added in version 10

    prependTo(target)jQuery

    targetSelectorElementjQuery

    A selector element HTML string or jQuery object the matched set ofelements will be inserted at the beginning of the element(s) specif iedby this parameter

    The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

    Consider the following HTML

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    We can create content and insert it into several elements at once

    $(ltpgtTestltpgt)prependTo(inner)

    Each inner ltdivgt element gets this new content

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

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

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Example 1 Prepends all spans to the element with the ID foo

    CSS

    div backgroundyellow

    Javascript

    $(span)prependTo(foo) check prepend() examples

    HTML

    ltdiv id=foogtFOOltdivgt

    ltspangtI have something to say ltspangt

    prepend

    Insert content specif ied by the parameter to the beginning of each element in the set ofmatched elements

    Added in version 14

    prepend(funct ion(index html))jQuery

    funct ion(indexhtml)Funct ion

    A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the beginning of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

    The prepend() method inserts the specif ied content as the f irst child of each element in thejQuery collect ion (To insert it as the last child use append())

    The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

    Consider the following HTML

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    You can create content and insert it into several elements at once

    $(inner)prepend(ltpgtTestltpgt)

    Each ltdiv class=innergt element gets this new content

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

    You can also select an element on the page and insert it into another

    $(container)prepend($(h2))

    If a single element selected this way is inserted elsewhere it will be moved into the target (notcloned)

    ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    Important If there is more than one target element however cloned copies of the insertedelement will be created for each target af ter the f irst

    Additional Arguments

    Similar to other content-adding methods such as append() and before() prepend() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

    For example the following will insert two new ltdivgts and an exist ing ltdivgt as the f irst threechild nodes of the body

    var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

    $(body)prepend($newdiv1 [newdiv2 existingdiv1])

    Since prepend() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

    $(body)prepend($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

    Example 1 Prepends some HTML to all paragraphs

    Javascript

    $(p)prepend(ltbgtHello ltbgt)

    CSS

    p backgroundyellow

    HTML

    ltpgtthere friendltpgt

    ltpgtamigoltpgt

    Example 2 Prepends a DOM Element to all paragraphs

    Javascript

    $(p)prepend(documentcreateTextNode(Hello ))

    CSS

    p backgroundyellow

    HTML

    ltpgtis what Id sayltpgtltpgtis what I saidltpgt

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

    Javascript

    $(p)prepend( $(b) )

    CSS

    p backgroundyellow

    HTML

    ltpgt is what was saidltpgtltbgtHelloltbgt

    appendTo

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

    Added in version 10

    appendTo(target)jQuery

    targetSelectorElementjQuery

    A selector element HTML string or jQuery object the matched set ofelements will be inserted at the end of the element(s) specif ied by thisparameter

    The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

    Consider the following HTML

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    We can create content and insert it into several elements at once

    $(ltpgtTestltpgt)appendTo(inner)

    Each inner ltdivgt element gets this new content

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Example 1 Appends all spans to the element with the ID foo

    Javascript

    $(span)appendTo(foo) check append() examples

    CSS

    foo backgroundyellow

    HTML

    ltspangtI have nothing more to say ltspangt

    ltdiv id=foogtFOO ltdivgt

    append

    Insert content specif ied by the parameter to the end of each element in the set of matchedelements

    Added in version 14

    append(funct ion(index html))jQuery

    funct ion(indexhtml)Funct ion

    A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the end of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

    The append() method inserts the specif ied content as the last child of each element in thejQuery collect ion (To insert it as the first child use prepend())

    The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

    Consider the following HTML

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

    You can create content and insert it into several elements at once

    $(inner)append(ltpgtTestltpgt)

    Each inner ltdivgt element gets this new content

    lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

    ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

    If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

    Additional Arguments

    Similar to other content-adding methods such as prepend() and before() append() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

    For example the following will insert two new ltdivgts and an exist ing ltdivgt as the last threechild nodes of the body

    var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

    $(body)append($newdiv1 [newdiv2 existingdiv1])

    Since append() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

    $(body)append($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

    Example 1 Appends some HTML to all paragraphs

    Javascript

    $(p)append(ltstronggtHelloltstronggt)

    CSS

    p backgroundyellow

    HTML

    ltpgtI would l ike to say ltpgt

    Example 2 Appends an Element to all paragraphs

    Javascript

    $(p)append(documentcreateTextNode(Hello))

    CSS

    p backgroundyellow

    HTML

    ltpgtI would l ike to say ltpgt

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

    Javascript

    $(p)append( $(strong) )

    CSS

    p backgroundyellow

    HTML

    ltstronggtHello worldltstronggtltpgtI would l ike to say ltpgt

    val see Attributes

    val see Attributes

    text

    Get the combined text contents of each element in the set of matched elements includingtheir descendants

    Added in version 10

    text()String

    Unlike the html() method text() can be used in both XML and HTML documents The result ofthe text() method is a string containing the combined text of all matched elements (Due tovariat ions in the HTML parsers in dif ferent browsers the text returned may vary in newlines andother white space) Consider the following HTML

    ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgt ltdivgt

    The code $(divdemo-container)text() would produce the following result

    Demonstrat ion Box list item 1 list item 2

    The text() method cannot be used on form inputs or scripts To set or get the text value ofinput or textarea elements use the val() method To get the value of a script element use thehtml() method

    As of jQuery 14 the text() method returns the value of text and CDATA nodes as well aselement nodes

    Example 1 Find the text in the f irst paragraph (stripping out the html) then set the html of thelast paragraph to show it is just text (the red bold is gone)

    Javascript

    var str = $(pfirst)text() $(plast)html(str)

    CSS

    p colorblue margin8px b colorred

    HTML

    ltpgtltbgtTestltbgt Paragraphltpgt

    ltpgtltpgt

    text

    Set the content of each element in the set of matched elements to the specif ied text

    Added in version 14

    text(funct ion(index text))jQuery

    funct ion(indextext)Funct ion

    A funct ion returning the text content to set Receives the indexposit ion of the element in the set and the old text value as arguments

    Unlike the html() method text() 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 willrender correct ly in HTML To do so it calls the DOM method createTextNode() which replacesspecial characters with their HTML ent ity equivalents (such as amplt for lt) Consider the followingHTML

    ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgtltdivgt

    The code $(divdemo-container)text(ltpgtThis is a test ltpgt) will produce the following DOMoutput

    ltdiv class=demo-containergtampltpampgtThis is a testampltpampgtltdivgt

    It will appear on a rendered page as though the tags were exposed like this

    ltpgtThis is a testltpgt

    The text() method cannot be used on input elements For input f ield text use the val() method

    As of jQuery 14 the text() method allows us to set the text content by passing in a funct ion

    $(ul l i )text(function(index) return item number + (index + 1))

    Given an unordered list with three ltligt elements this example will produce the following DOMoutput

    ltulgt ltligtitem number 1ltligt ltligtitem number 2ltligt ltligtitem number 3ltligtltulgt

    Example 1 Add text to the paragraph (not ice the bold tag is escaped)

    Javascript

    $(p)text(ltbgtSomeltbgt new text)

    CSS

    p colorblue margin8px

    HTML

    ltpgtTest Paragraphltpgt

    html see Attributes

    html see Attributes

    toggleClass see Attributes

    removeClass see Attributes

    hasClass see Attributes

    removeAttr see Attributes

    attr see Attributes

    attr see Attributes

    addClass see Attributes

    Data

    jQueryhasData

    Determine whether an element has any jQuery data associated with it

    Added in version 15

    jQueryhasData(element)Boolean

    elementElement A DOM element to be checked for data

    The jQueryhasData() method provides a way to determine if an element current ly has anyvalues that were set using jQuerydata() If no data is associated with an element (there is nodata object at all or the data object is empty) the method returns false otherwise it returnstrue

    The primary advantage of jQueryhasData(element) is that it does not create and associate adata object with the element if none current ly exists In contrast jQuerydata(element) alwaysreturns a data object to the caller creat ing one if no data object previously existed

    Example 1 Set data on an element and see the results of hasData

    Javascript

    $(function() var $p = jQuery(p) p = $p[0] $pappend(jQueryhasData(p)+ ) false jQuerydata(p testing 123) $pappend(jQueryhasData(p)+ ) true jQueryremoveData(p testing) $pappend(jQueryhasData(p)+ ) false )

    HTML

    ltpgtResults ltpgt

    jQueryremoveData

    Remove a previously-stored piece of data

    Added in version 123

    jQueryremoveData(element name)jQuery

    elementElement A DOM element f rom which to remove data

    nameString (opt ional) A string naming the piece of data to remove

    Note This is a low-level method you should probably use removeData() instead

    The jQueryremoveData() method allows us to remove values that were previously set usingjQuerydata() When called with the name of a key jQueryremoveData() deletes that part icularvalue when called with no arguments all values are removed

    Example 1 Set a data store for 2 names then remove one of them

    Javascript

    var div = $(div)[0]$(spaneq(0))text( + $(div)data(test1))jQuerydata(div test1 VALUE-1)jQuerydata(div test2 VALUE-2)$(spaneq(1))text( + jQuerydata(div test1))jQueryremoveData(div test1)$(spaneq(2))text( + jQuerydata(div test1))$(spaneq(3))text( + jQuerydata(div test2))

    CSS

    div margin2px colorblue span colorred

    HTML

    ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt ltdivgtvalue2 after removal ltspangtltspangtltdivgt

    jQuerydata

    Store arbit rary data associated with the specif ied element Returns the value that was set

    Added in version 123

    jQuerydata(element key value)Object

    elementElement The DOM element to associate with the data

    keyString A string naming the piece of data to set

    valueObject The new data value

    Note This is a low-level method a more convenient data() is also available

    The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f ree from memory leaks jQuery ensures that thedata is removed when DOM elements are removed via jQuery methods and when the userleaves the page We can set several dist inct values for a single element and retrieve them later

    jQuerydata(documentbody foo 52)jQuerydata(documentbody bar test)

    Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

    Example 1 Store then retrieve a value from the div element

    Javascript

    var div = $(div)[0] jQuerydata(div test first 16 last pizza ) $(spanfirst)text(jQuerydata(div test)first) $(spanlast)text(jQuerydata(div test)last)

    CSS

    div colorblue span colorred

    HTML

    ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

    jQuerydata

    Returns value at named data store for the element as set by jQuerydata(element namevalue) or the full data store for the element

    Added in version 14

    jQuerydata(element)Object

    elementElement The DOM element to query for the data

    Note This is a low-level method a more convenient data() is also available

    Regarding HTML5 data- at t ributes This low-level method does NOT retrieve the data-at t ributes unless the more convenient data() method has already retrieved them

    The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f rom memory leaks We can retrieve severaldist inct values for a single element one at a t ime or as a set

    alert(jQuerydata( documentbody foo ))alert(jQuerydata( documentbody ))

    The above lines alert the data values that were set on the body element If nothing was set onthat element an empty string is returned

    Calling jQuerydata(element) retrieves all of the element s associated values as a JavaScriptobject Note that jQuery itself uses this method to store data for internal use such as eventhandlers so do not assume that it contains only data that your own code has stored

    Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

    Example 1 Get the data named blah stored at for an element

    Javascript

    $(button)cl ick(function(e) var value div = $(div)[0]

    switch ($(button)index(this)) case 0 value = jQuerydata(div blah) break case 1 jQuerydata(div blah hello) value = Stored break case 2 jQuerydata(div blah 86) value = Stored break case 3 jQueryremoveData(div blah) value = Removed break

    $(span)text( + value))

    CSS

    div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

    HTML

    ltdivgtA divltdivgtltbuttongtGet blah from the divltbuttongtltbuttongtSet blah to helloltbuttongt

    ltbuttongtSet blah to 86ltbuttongtltbuttongtRemove blah from the divltbuttongtltpgtThe blah value of this div is ltspangtltspangtltpgt

    jQuerydequeue

    Execute the next funct ion on the queue for the matched element

    Added in version 13

    jQuerydequeue(element queueName)jQuery

    elementElement A DOM element f rom which to remove and execute a queuedfunct ion

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    Note This is a low-level method you should probably use dequeue() instead

    When jQuerydequeue() is called the next funct ion on the queue is removed from the queueand then executed This funct ion should in turn (direct ly or indirect ly) cause jQuerydequeue() tobe called so that the sequence can cont inue

    Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

    Javascript

    $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $dequeue( this ) ) $(div)animate(left10px top30px 700) )

    CSS

    div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

    HTML

    ltbuttongtStartltbuttongt ltdivgtltdivgt

    jQueryqueue

    Show the queue of funct ions to be executed on the matched element

    Added in version 13

    jQueryqueue(element queueName)Array

    elementElement A DOM element to inspect for an at tached queue

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    Note This is a low-level method you should probably use queue() instead

    Example 1 Show the length of the queue

    Javascript

    $(show)cl ick(function () var n = jQueryqueue( $(div)[0] fx ) $(span)text(Queue length is + nlength) ) function runIt() $(div)show(slow) $(div)animate(left+=2002000) $(div)sl ideToggle(1000) $(div)sl ideToggle(fast) $(div)animate(left-=2001500) $(div)hide(slow) $(div)show(1200) $(div)sl ideUp(normal runIt) runIt()

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue span colorred

    HTML

    ltbutton id=showgtShow Length of Queueltbuttongt ltspangtltspangt ltdivgtltdivgt

    jQueryqueue

    Manipulate the queue of funct ions to be executed on the matched element

    Added in version 13

    jQueryqueue(element queueName callback())jQuery

    elementElement A DOM element on which to add a queued funct ion

    queueNameString A string containing the name of the queue Defaults to fx thestandard ef fects queue

    callback()Funct ion The new funct ion to add to the queue

    Note This is a low-level method you should probably use queue() instead

    Every element can have one or more queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion

    The jQueryqueue() method allows us to direct ly manipulate this queue of funct ions CallingjQueryqueue() with a callback is part icularly useful it allows us to place a new funct ion at theend of the queue

    Note that when adding a funct ion with jQueryqueue() we should ensure that jQuerydequeue()is eventually called so that the next funct ion in line executes

    Example 1 Queue a custom funct ion

    Javascript

    $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=200500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() )

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

    HTML

    Click here ltdivgtltdivgt

    Example 2 Set a queue array to delete the queue

    Javascript

    $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=2001500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() ) $(stop)cl ick(function () jQueryqueue( $(div)[0] fx [] ) $(div)stop() )

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

    HTML

    ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

    clearQueue

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

    Added in version 14

    clearQueue(queueName)jQuery

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    When the clearQueue() method is called all funct ions on the queue that have not beenexecuted are removed from the queue When used without an argument clearQueue()removes the remaining funct ions from fx the standard ef fects queue In this way it is similar tostop(true) However while the stop() method is meant to be used only with animat ionsclearQueue() can also be used to remove any funct ion that has been added to a genericjQuery queue with the queue() method

    Example 1 Empty the queue

    Javascript

    $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp())$(stop)cl ick(function () $(div)clearQueue() $(div)stop())

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

    HTML

    ltbutton id=startgtStartltbuttongtltbutton id=stopgtStopltbuttongtltdivgtltdivgt

    removeData

    Remove a previously-stored piece of data

    Added in version 123

    removeData(name)jQuery

    nameString (opt ional) A string naming the piece of data to delete

    The removeData() method allows us to remove values that were previously set using data()When called with the name of a key removeData() deletes that part icular value when calledwith no arguments all values are removed

    NOTE Start ing with jQuery 143 calling removeData() will cause the value of the propertybeing removed to revert to the value of the data at t ribute of the same name in the DOM ratherthan being set to undef ined

    Example 1 Set a data store for 2 names then remove one of them

    Javascript

    $(spaneq(0))text( + $(div)data(test1)) $(div)data(test1 VALUE-1) $(div)data(test2 VALUE-2) $(spaneq(1))text( + $(div)data(test1)) $(div)removeData(test1) $(spaneq(2))text( + $(div)data(test1)) $(spaneq(3))text( + $(div)data(test2))

    CSS

    div margin2px colorblue span colorred

    HTML

    ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt

    ltdivgtvalue2 after removal ltspangtltspangtltdivgt

    data

    Store arbit rary data associated with the matched elements

    Added in version 143

    data(obj)jQuery

    objObject An object of key-value pairs of data to update

    The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks

    We can set several dist inct 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 143 sett ing an element s data object with data(obj) extends the data previouslystored with that element jQuery itself uses the data() method to save informat ion under thenames events and handle and also reserves any data name start ing with an underscore (_)for internal use

    Prior to jQuery 143 (start ing in jQuery 14) the data() method completely replaced all datainstead of just extending the data object If you are using third-party plugins it may not beadvisable to completely replace the element s data object since plugins may have also setdata

    Due to the way browsers interact with plugins and external code the data() method cannot beused on ltobjectgt (unless it s a Flash plugin) ltappletgt or ltembedgt elements

    Example 1 Store then retrieve a value from the div element

    Javascript

    $(div)data(test first 16 last pizza )$(spanfirst)text($(div)data(test)first)$(spanlast)text($(div)data(test)last)

    CSS

    div colorblue span colorred

    HTML

    ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

    data

    Returns value at named data store for the f irst element in the jQuery collect ion as set bydata(name value)

    Added in version 14

    data()Object

    The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks We can retrieve several dist inctvalues for a single element one at a t ime or as a set

    alert($(body)data(foo))alert($(body)data())

    The above lines alert the data values that were set on the body element If no data at all wasset on that element undef ined is returned

    alert( $(body)data(foo)) undefined$(body)data(bar foobar)alert( $(body)data(foobar)) foobar

    HTML 5 data- Attributes

    As of jQuery 143 HTML 5 data- at t ributes will be automat ically pulled in to jQuerys data object The treatment of at t ributes with embedded dashes was changed in jQuery 16 to conform tothe W3C HTML5 specif icat ion

    For example given the following HTML

    ltdiv data-role=page data-last-value=43 data-hidden=true data-options=nameJohngtltdivgt

    All of the following jQuery code will work

    $(div)data(role) === page$(div)data(lastValue) === 43$(div)data(hidden) === true$(div)data(options)name === John

    Every at tempt is made to convert the string to a JavaScript value (this includes booleansnumbers objects arrays and null) otherwise it is lef t as a string To retrieve the valuesat t ribute as a string without any at tempt to convert it use the at t r() method When the dataattribute is an object (starts with ) or array (starts with [) then jQueryparseJSON is used toparse the string it must follow valid JSON syntax including quoted property names The data-at t ributes are pulled in the f irst t ime the data property is accessed and then are no longeraccessed or mutated (all data values are then stored internally in jQuery)

    Calling data() with no parameters retrieves all of the values as a JavaScript object This objectcan be safely cached in a variable as long as a new object is not set with data(obj) Using theobject direct ly to get or set values is faster than making individual calls to data() to get or seteach value

    var mydata = $(mydiv)data()if ( mydatacount lt 9 ) mydatacount = 43 mydatastatus = embiggened

    Example 1 Get the data named blah stored at for an element

    Javascript

    $(button)cl ick(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))

    CSS

    div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

    HTML

    ltdivgtA divltdivgt ltbuttongtGet blah from the divltbuttongt ltbuttongtSet blah to helloltbuttongt

    ltbuttongtSet blah to 86ltbuttongt ltbuttongtRemove blah from the divltbuttongt ltpgtThe blah value of this div is ltspangtltspangtltpgt

    dequeue

    Execute the next funct ion on the queue for the matched elements

    Added in version 12

    dequeue(queueName)jQuery

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    When dequeue() is called the next funct ion on the queue is removed from the queue and thenexecuted This funct ion should in turn (direct ly or indirect ly) cause dequeue() to be called sothat the sequence can cont inue

    Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

    Javascript

    $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $(this)dequeue() ) $(div)animate(left10px top30px 700))

    CSS

    div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

    HTML

    ltbuttongtStartltbuttongt ltdivgtltdivgt

    queue

    Show the queue of funct ions to be executed on the matched elements

    Added in version 12

    queue(queueName)Array

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    Example 1 Show the length of the queue

    Javascript

    var div = $(div)

    function runIt() divshow(slow) divanimate(left+=2002000) divsl ideToggle(1000) divsl ideToggle(fast) divanimate(left-=2001500) divhide(slow) divshow(1200) divsl ideUp(normal runIt)

    function showIt() var n = divqueue(fx) $(span)text( nlength ) setTimeout(showIt 100)

    runIt()showIt()

    CSS

    div margin3px width40px height40px positionabsolute left0px top60px backgroundgreen displaynone divnewcolor backgroundblue p colorred

    HTML

    ltpgtThe queue length is ltspangtltspangtltpgt ltdivgtltdivgt

    queue

    Manipulate the queue of funct ions to be executed on the matched elements

    Added in version 12

    queue(queueName callback( next ))jQuery

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    callback( next)Funct ion

    The new funct ion to add to the queue with a funct ion to call thatwill dequeue the next item

    Every element can have one to many queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion The typical exampleof this is calling mult iple animat ion methods on an element For example

    $(foo)sl ideUp()fadeIn()

    When this statement is executed the element begins its sliding animat ion immediately but thefading transit ion is placed on the fx queue to be called only once the sliding transit ion iscomplete

    The queue() method allows us to direct ly manipulate this queue of funct ions Calling queue()with a callback is part icularly useful it allows us to place a new funct ion at the end of thequeue

    This feature is similar to providing a callback funct ion with an animat ion method but does notrequire the callback to be given at the t ime the animat ion is performed

    $(foo)sl ideUp()$(foo)queue(function() alert(Animation complete) $(this)dequeue())

    This is equivalent to

    $(foo)sl ideUp(function() alert(Animation complete))

    Note that when adding a funct ion with queue() we should ensure that dequeue() is eventuallycalled so that the next funct ion in line executes

    In jQuery 14 the funct ion that s called is passed in another funct ion as the f irst argument thatwhen called automat ically dequeues the next item and keeps the queue moving You would useit like so

    $(test)queue(function(next) Do some stuff next())

    Example 1 Queue a custom funct ion

    Javascript

    $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=200500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() )

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

    HTML

    Click here ltdivgtltdivgt

    Example 2 Set a queue array to delete the queue

    Javascript

    $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() ) $(stop)cl ick(function () $(div)queue(fx []) $(div)stop() )

    CSS

    div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

    HTML

    ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

    Forms

    submit

    Bind an event handler to the submit JavaScript event or t rigger that event on an element

    Added in version 10

    submit()jQuery

    This method is a shortcut for bind(submit handler) in the f irst variat ion and t rigger(submit ) inthe third

    The submit event is sent to an element when the user is at tempt ing to submit a form It canonly be at tached to ltformgt elements Forms can be submit ted either by clicking an explicitltinput type=submitgt ltinput type=imagegt or ltbutton type=submitgt or by pressing

    Enter when certain form elements have focus

    Depending on the browser the Enter key may only cause a form submission if theform has exactly one text field or only when there is a submit button present Theinterface should not rely on a particular behavior for this key unless the issue isforced by observing the keypress event for presses of the Enter key

    For example consider the HTML

    ltform id=target action=destinationhtmlgt ltinput type=text value=Hello there gt ltinput type=submit value=Go gtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the form

    $(target)submit(function() alert(Handler for submit() called) return false)

    Now when the form is submit ted the message is alerted This happens prior to the actualsubmission so we can cancel the submit act ion by calling preventDefault () on the event objector by returning false f rom our handler We can trigger the event manually when another elementis clicked

    $(other)cl ick(function() $(target)submit())

    After this code executes clicks on Trigger the handler will also display the message In addit ionthe default submit act ion on the form will be f ired so the form will be submit ted

    The JavaScript submit event does not bubble in Internet Explorer However scripts that rely onevent delegat ion with the submit event will work consistent ly across browsers as of jQuery 14which has normalized the event s behavior

    Example 1 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

    Javascript

    $(form)submit(function() i f ($(inputfirst)val() == correct) $(span)text(Validated)show() return true $(span)text(Not valid)show()fadeOut(1000) return false )

    CSS

    p margin0 colorblue divp margin-left10px span colorred

    HTML

    ltpgtType correct to validateltpgt ltform action=javascriptalert(success)gt ltdivgt ltinput type=text gt

    ltinput type=submit gt ltdivgt ltformgt ltspangtltspangt

    Example 2 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

    Javascript

    $(form)submit( function () return thissome_flag_variable )

    Example 3 To trigger the submit event on the f irst form on the page t ry

    Javascript

    $(formfirst)submit()

    select

    Bind an event handler to the select JavaScript event or t rigger that event on an element

    Added in version 10

    select()jQuery

    This method is a shortcut for bind(select handler) in the f irst two variat ions andtrigger(select ) in the third

    The select event is sent to an element when the user makes a text select ion inside it Thisevent is limited to ltinput type=textgt f ields and lttextareagt boxes

    For example consider the HTML

    ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the text input

    $(target)select(function() alert(Handler for select() called))

    Now when any port ion of the text is selected the alert is displayed Merely set t ing the locat ionof the insert ion point will not t rigger the event To trigger the event manually apply select()without an argument

    $(other)cl ick(function() $(target)select())

    After this code executes clicks on the Trigger button will also alert the message

    Handler for select() called

    In addit ion the default select act ion on the f ield will be f ired so the ent ire text f ield will beselected

    The method for retrieving the current selected text differs from one browser toanother A number of jQuery plug-ins offer cross-platform solutions

    Example 1 To do something when text in input boxes is selected

    Javascript

    $(input)select( function () $(div)text(Something was selected)show()fadeOut(1000) )

    CSS

    p colorblue div colorred

    HTML

    ltpgt

    Click and drag the mouse to select text in the inputs ltpgt ltinput type=text value=Some text gt ltinput type=text value=to test on gt

    ltdivgtltdivgt

    Example 2 To trigger the select event on all input elements t ry

    Javascript

    $(input)select()

    change

    Bind an event handler to the change JavaScript event or t rigger that event on an element

    Added in version 10

    change()jQuery

    This method is a shortcut for bind(change handler) in the f irst two variat ions andtrigger(change) in the third

    The change event is sent to an element when its value changes This event is limited to ltinputgtelements lttextareagt boxes and ltselectgt elements For select boxes checkboxes and radiobuttons the event is f ired immediately when the user makes a select ion with the mouse butfor the other element types the event is deferred unt il the element loses focus

    For example consider the HTML

    ltformgt ltinput class=target type=text value=Field 1 gt ltselect class=targetgt ltoption value=option1 selected=selectedgtOption 1ltoptiongt ltoption value=option2gtOption 2ltoptiongt ltselectgtltformgtltdiv id=othergt Trigger the handlerltdivgt

    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 opt ion is selected from the dropdown the alert is displayed It is alsodisplayed if you change the text in the f ield and then click away If the f ield loses focus withoutthe contents having changed though the event is not t riggered To trigger the event manuallyapply change() without arguments

    $(other)cl ick(function() $( target)change())

    After this code executes clicks on Trigger the handler will also alert the message The messagewill display twice because the handler has been bound to the change event on both of theform elements

    As of jQuery 14 the change event bubbles in Internet Explorer behaving consistent ly with theevent in other modern browsers

    Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

    Javascript

    $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) change()

    CSS

    div colorred

    HTML

    ltselect name=sweets multiple=multiplegt ltoptiongtChocolateltoptiongt ltoption selected=selectedgtCandyltoptiongt

    ltoptiongtTaffyltoptiongt ltoption selected=selectedgtCaramelltoptiongt ltoptiongtFudgeltoptiongt ltoptiongtCookieltoptiongt

    ltselectgt ltdivgtltdivgt

    Example 2 To add a validity test to all text input elements

    Javascript

    $(input[type=text])change( function() check input ($(this)val()) for validity here)

    blur

    Bind an event handler to the blur JavaScript event or t rigger that event on an element

    Added in version 10

    blur()jQuery

    This method is a shortcut for bind(blur handler) in the f irst two variat ions and t rigger(blur) inthe third

    The blur event is sent to an element when it loses focus Originally this event was only

    applicable to form elements such as ltinputgt In recent browsers the domain of the event hasbeen extended to include all element types An element can lose focus via keyboardcommands such as the Tab key or by mouse clicks elsewhere on the page

    For example consider the HTML

    ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgtThe event handler can be bound to the first input field$(target)blur(function() alert(Handler for blur() called))

    Now if the f irst f ield has the focus clicking elsewhere or tabbing away from it displays the alert

    Handler for blur() called

    To trigger the event programmatically apply blur() without an argument

    $(other)cl ick(function() $(target)blur())

    After this code executes clicks on Trigger the handler will also alert the message

    The blur event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the blur event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping blur to the focusout event in its eventdelegat ion methods live() and delegate()

    Example 1 To trigger the blur event on all paragraphs

    Javascript

    $(p)blur()

    focus

    Bind an event handler to the focus JavaScript event or t rigger that event on an element

    Added in version 10

    focus()jQuery

    This method is a shortcut for bind(focus handler) in the f irst and second variat ionsand t rigger(focus) in the third

    The focus event is sent to an element when it gains focus This event is implicit lyapplicable to a limited set of elements such as form elements (ltinputgt ltselectgt etc) andlinks (lta hrefgt) In recent browser versions the event can be extended to include allelement types by explicit ly set t ing the element s tabindex property An element can gainfocus via keyboard commands such as the Tab key or by mouse clicks on the element

    Elements with focus are usually highlighted in some way by the browser for examplewith a dotted line surrounding the element The focus is used to determine which elementis the f irst to receive keyboard-related events

    For example consider the HTML

    ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the f irst input f ield

    $(target)focus(function() alert(Handler for focus() called))

    Now clicking on the f irst f ield or tabbing to it f rom another f ield displays the alert

    Handler for focus() called

    We can trigger the event when another element is clicked

    $(other)cl ick(function() $(target)focus())

    After this code executes clicks on Trigger the handler will also alert the message

    The focus event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the focus event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping focus to the focusin event in its event

    delegat ion methods live() and delegate()

    Triggering the focus on hidden elements causes an error in Internet ExplorerTake care to only call focus() without parameters on elements that are visible

    Example 1 Fire focus

    CSS

    span displaynone

    Javascript

    $(input)focus(function () $(this)next(span)css(display inl ine)fadeOut(1000) )

    HTML

    ltpgtltinput type=text gt ltspangtfocus fireltspangtltpgt

    ltpgtltinput type=password gt ltspangtfocus fireltspangtltpgt

    Example 2 To stop people f rom writ ing in text input boxes t ry

    Javascript

    $(input[type=text])focus(function() $(this)blur())

    Example 3 To focus on a login input box with id login on page startup t ry

    Javascript

    $(document)ready(function() $(login)focus())

    serializeArray

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

    Added in version 12

    serializeArray()Array

    The serializeArray() method creates a JavaScript array of objects ready to be encoded as aJSON string It operates on a jQuery object represent ing a set of form elements The formelements can be of several types

    ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

    The serializeArray() method uses the standard W3C rules for successful controls to determinewhich elements it should include in part icular the element cannot be disabled and must containa name attribute No submit button value is serialized since the form was not submit ted using abutton Data f rom f ile select elements is not serialized

    This method can act on a jQuery object that has selected individual form elements such asltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgt tag itselffor serializat ion

    $(form)submit(function() consolelog($(this)serial izeArray()) return false)

    This produces the following data structure (provided that the browser supports consolelog)

    [ name a value 1 name b value 2 name c value 3 name d value 4 name e value 5 ]

    Example 1 Get the values from a form iterate through them and append them to a resultsdisplay

    Javascript

    function showValues() var fields = $(input)serial izeArray() $(results)empty() jQueryeach(fields function(i field) $(results)append(fieldvalue + ) )

    $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

    CSS

    body select font-size14px form margin5px p colorred margin5px b colorblue

    HTML

    ltpgtltbgtResultsltbgt ltspan id=resultsgtltspangtltpgt

    ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

    ltselectgt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

    ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

    ltlabel for=ch1gtcheck1ltlabelgt ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

    ltlabel for=ch2gtcheck2ltlabelgt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

    ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

    ltlabel for=r2gtradio2ltlabelgt ltformgt

    serialize

    Encode a set of form elements as a string for submission

    Added in version 10

    serialize()String

    The serialize() method creates a text string in standard URL-encoded notat ion It operates ona jQuery object represent ing a set of form elements The form elements can be of severaltypes

    ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

    The serialize() method can act on a jQuery object that has selected individual form elementssuch as ltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgttag itself for serializat ion

    $(form)submit(function() alert($(this)serial ize()) return false)

    This produces a standard-looking query string

    a=1ampb=2ampc=3ampd=4ampe=5

    Warning select ing both the form and its children will cause duplicates in the serialized string

    Note Only successful controls are serialized to the string No submit button value is serializedsince the form was not submit ted using a button For a form element s value to be included inthe serialized string the element must have a name attribute Values from checkboxes andradio buttons (inputs of type radio or checkbox) are included only if they are checked Datafrom f ile select elements is not serialized

    Example 1 Serialize a form to a query string that could be sent to a server in an Ajax request

    Javascript

    function showValues() var str = $(form)serial ize() $(results)text(str) $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

    CSS

    body select font-size12px form margin5px p colorred margin5px font-size14px b colorblue

    HTML

    ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

    ltbr gt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

    ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

    ltlabel for=ch1gtcheck1ltlabelgt

    ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

    ltlabel for=ch2gtcheck2ltlabelgtltbr gt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

    ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

    ltlabel for=r2gtradio2ltlabelgt ltformgt ltpgtlttt id=resultsgtltttgtltpgt

    jQueryparam

    Create a serialized representat ion of an array or object suitable for use in a URL query string orAjax request

    Added in version 14

    jQueryparam(obj t radit ional)String

    objArray Object An array or object to serialize

    t radit ionalBoolean A Boolean indicat ing whether to perform a tradit ional shallowserializat ion

    This funct ion is used internally to convert form element values into a serialized stringrepresentat ion (See serialize() for more informat ion)

    As of jQuery 13 the return value of a funct ion is used instead of the funct ion as a String

    As of jQuery 14 the $param() method serializes deep objects recursively to accommodatemodern script ing languages and frameworks such as PHP and Ruby on Rails You can disablethis funct ionality globally by sett ing jQueryajaxSett ingst radit ional = t rue

    If the object passed is in an Array it must be an array of objects in the format returned byserializeArray()

    [namefirstvalueRicknamelastvalueAstleynamejobvalueRock Star]

    Note Because some frameworks have limited ability to parse serialized arraysdevelopers should exercise caution when passing an obj argument that containsobjects or arrays nested within another array

    Note Because there is no universally agreed-upon specification for param stringsit is not possible to encode complex data structures using this method in a mannerthat works ideally across all languages supporting such input Until such time thatthere is the $param method will remain in its current form

    In jQuery 14 HTML5 input elements are also serialized

    We can display a query string representat ion of an object and a URI-decoded version of the

    same as follows

    var myObject = a one 1 two 2 three 3 b [123]var recursiveEncoded = $param(myObject)var recursiveDecoded = decodeURIComponent($param(myObject))

    alert(recursiveEncoded)alert(recursiveDecoded)

    The values of recursiveEncoded and recursiveDecoded are alerted as follows

    a5Bone5D=1ampa5Btwo5D=2ampa5Bthree5D=3ampb5B5D=1ampb5B5D=2ampb5B5D=3

    a[one]=1ampa[two]=2ampa[three]=3ampb[]=1ampb[]=2ampb[]=3

    To emulate the behavior of $param() prior to jQuery 14 we can set the t radit ional argument totrue

    var myObject = a one 1 two 2 three 3 b [123]var shallowEncoded = $param(myObject true)var shallowDecoded = decodeURIComponent(shallowEncoded)

    alert(shallowEncoded)alert(shallowDecoded)

    The values of shallowEncoded and shallowDecoded are alerted as follows

    a=5Bobject+Object5Dampb=1ampb=2ampb=3

    a=[object+Object ]ampb=1ampb=2ampb=3

    Example 1 Serialize a keyvalue object

    Javascript

    var params = width1680 height1050 var str = jQueryparam(params) $(results)text(str)

    CSS

    div colorred

    HTML

    ltdiv id=resultsgtltdivgt

    Example 2 Serialize a few complex objects

    Javascript

    lt=132 $param( a [234] ) a=2ampa=3ampa=4 gt=14$param( a [234] ) a[]=2ampa[]=3ampa[]=4

    lt=132 $param( a b1c2 d [34 e5 ] ) a=[object+Object]ampd=3ampd=4ampd=[object+Object] gt=14 $param( a b1c2 d [34 e5 ] ) a[b]=1ampa[c]=2ampd[]=3ampd[]=4ampd[2][e]=5

    CSS

    div colorred

    val see Attributes

    val see Attributes

    Events

    toggle

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

    Added in version 10

    toggle(handler(eventObject) handler(eventObject) handler(eventObject))jQuery

    handler(eventObject)Funct ion A funct ion to execute every even t ime the element isclicked

    handler(eventObject)Funct ion A funct ion to execute every odd t ime the element isclicked

    handler(eventObject)Funct ion (opt ional) Addit ional handlers to cycle through af terclicks

    The toggle() method binds a handler for the click event so the rules out lined for the t riggeringof click apply here as well

    For example consider the HTMLltdiv id=targetgt Click hereltdivgt

    Event handlers can then bebound to the ltdivgt

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

    First handler for toggle() called

    Second handler for toggle() called

    First handler for toggle() called

    Second handler for toggle() called

    First handler for toggle() called

    If more than two handlers are provided toggle() will cycle among all of them For example ifthere are three handlers then the f irst handler will be called on the f irst click the fourth clickthe seventh click and so on

    Note jQuery also provides an animation method named toggle() that toggles the

    visibility of elements Whether the animation or the event method is fired dependson the set of arguments passed

    The toggle() method is provided for convenience It is relat ively straightforward to implementthe same behavior by hand and this can be necessary if the assumptions built into toggle()prove limit ing For example toggle() is not guaranteed to work correct ly if applied twice to thesame element Since toggle() internally uses a click handler to do its work we must unbind clickto remove a behavior at tached with toggle() so other click handlers can be caught in thecrossf ire The implementat ion also calls preventDefault () on the event so links will not befollowed and buttons will not be clicked if toggle() has been called on the element

    Example 1 Click to toggle highlight on the list item

    Javascript

    $(l i)toggle( function () $(this)css(list-style-typedisc colorblue) function () $(this)css(list-style-typedisc colorred) function () $(this)css(list-style-type color) )

    CSS

    ul margin10px l ist-styleinside circle font-weightbold l i cursorpointer

    HTML

    ltulgt ltligtGo to the storeltligt ltligtPick up dinnerltligt ltligtDebug crashltligt

    ltligtTake a jogltligt ltulgt

    Example 2 To toggle a style on table cells

    Javascript

    Javascript

    $(td)toggle( function () $(this)addClass(selected) function () $(this)removeClass(selected) )

    eventnamespace

    The namespace specif ied when the event was triggered

    Added in version 143

    This will likely be used primarily by plugin authors who wish to handle tasks dif ferent lydepending on the event namespace used

    Example 1 Determine the event namespace used

    Javascript

    $(p)bind(testsomething function(event) alert( eventnamespace ))$(button)cl ick(function(event) $(p)trigger(testsomething))

    HTML

    ltbuttongtdisplay eventnamespaceltbuttongtltpgtltpgt

    undelegate

    Remove a handler f rom the event for all elements which match the current selector now or inthe future based upon a specif ic set of root elements

    Added in version 16

    undelegate(namespace)jQuery

    namespaceString A string containing a namespace to unbind all events f rom

    Undelegate is a way of removing event handlers that have been bound using delegate() Itworks virtually ident ically to die() with the addit ion of a selector f ilter argument (which isrequired for delegat ion to work)

    Example 1 Can bind and unbind events to the colored button

    Javascript

    function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(body)delegate(theone cl ick aClick) find(theone)text(Can Click))$(unbind)cl ick(function () $(body)undelegate(theone cl ick aClick) find(theone)text(Does nothing))

    CSS

    button margin5px buttontheone colorred backgroundyellow

    HTML

    ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongtltdiv style=displaynonegtClickltdivgt

    Example 2 To unbind all delegated events f rom all paragraphs write

    Javascript

    $(p)undelegate()

    Example 3 To unbind all delegated click events f rom all paragraphs write

    Javascript

    $(p)undelegate( cl ick )

    Example 4 To undelegate just one previously bound handler pass the funct ion in as the third

    argument

    Javascript

    var foo = function () code to handle some kind of event

    now foo wil l be called when paragraphs are cl icked $(body)delegate(p cl ick foo)

    foo wil l no longer be called$(body)undelegate(p cl ick foo)

    Example 5 To unbind all delegated events by their namespace

    Javascript

    var foo = function () code to handle some kind of event

    delegate events under the whatever namespace$(form)delegate(button cl ickwhatever foo)

    $(form)delegate(input[type=text] keypresswhatever foo)

    unbind all events delegated under the whatever namespace

    $(form)undelegate(whatever)

    delegate

    Attach a handler to one or more events for all elements that match the selector now or in thefuture based on a specif ic set of root elements

    Added in version 143

    delegate(selector events)jQuery

    selectorString A selector to f ilter the elements that t rigger the event

    eventsMap A map of one or more event types and funct ions to execute for them

    Delegate is an alternat ive to using the live() method allowing for each binding of eventdelegat ion to specif ic DOM elements For example the following delegate code

    $(table)delegate(td hover function() $(this)toggleClass(hover))

    Is equivalent to the following code writ ten using live()

    $(table)each(function() $(td this)l ive(hover function() $(this)toggleClass(hover) ))

    See also the undelegate() method for a way of removing event handlers added in delegate()

    Passing and handling event data works the same way as it does for bind()

    Example 1 Click a paragraph to add another Note that delegate() binds the click event to allparagraphs - even new ones

    Javascript

    $(body)delegate(p cl ick function() $(this)after(ltpgtAnother paragraphltpgt) )

    CSS

    p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

    HTML

    ltpgtClick meltpgt

    ltspangtltspangt

    Example 2 To display each paragraphs text in an alert box whenever it is clicked

    Javascript

    $(body)delegate(p cl ick function() alert( $(this)text() ))

    Example 3 To cancel a default act ion and prevent it f rom bubbling up return false

    Javascript

    $(body)delegate(a cl ick function() return false )

    Example 4 To cancel only the default act ion by using the preventDefault method

    Javascript

    $(body)delegate(a cl ick function(event) eventpreventDefault())

    Example 5 Can bind custom events too

    Javascript

    $(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)cl ick(function () $(p)trigger(myCustomEvent) )

    CSS

    p colorred span colorblue

    HTML

    ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

    jQueryproxy

    Takes a funct ion and returns a new one that will always have a part icular context

    Added in version 14

    jQueryproxy(context name)Funct ion

    context Object The object to which the context of the funct ion should be set

    nameString The name of the funct ion whose context will be changed (should be aproperty of the context object)

    This method is most useful for at taching event handlers to an element where the context ispoint ing back to a dif ferent object Addit ionally jQuery makes sure that even if you bind thefunct ion returned from jQueryproxy() it will st ill unbind the correct funct ion if passed theoriginal

    Example 1 Change the context of funct ions bound to a click handler using the funct ioncontext signature Unbind the f irst handler af ter f irst click

    HTML

    ltpgtltbutton type=button id=testgtTestltbuttongtltpgtltdiv id=loggtltdivgt

    Javascript

    var me = type zombie test function(event) Without proxy `this` would refer to the event target use eventtarget to reference that element var element = eventtarget $(element)css(background-color red)

    With proxy `this` refers to the me object encapsulating this function $(log)append( Hello + thistype + ltbrgt ) $(test)unbind(click thistest)

    var you = type person test function(event) $(log)append( thistype + )

    execute youtest() in the context of the `you` object no matter where it is called i e the `this` keyword wil l refer to `you`var youClick = $proxy( youtest you )

    attach click handlers to test$(test) this === zombie handler unbound after first cl ick cl ick( $proxy( metest me ) ) this === person cl ick( youClick ) this === zombie cl ick( $proxy( youtest me ) ) this === ltbuttongt element cl ick( youtest )

    Example 2 Enforce the context of the funct ion using the context funct ion name signatureUnbind the handler af ter f irst click

    HTML

    ltpgtltbutton id=testgtTestltbuttongtltpgt ltp id=loggtltpgt

    Javascript

    var obj = name John test function() $(log)append( thisname ) $(test)unbind(click objtest)

    $(test)cl ick( jQueryproxy( obj test ) )

    focusout

    Bind an event handler to the focusout JavaScript event

    Added in version 143

    focusout(eventData handler(eventObject))jQuery

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

    This method is a shortcut for bind(focusout handler)

    The focusout event is sent to an element when it or any element inside of it loses focus Thisis dist inct f rom the blur event in that it supports detect ing the loss of focus from parentelements (in other words it supports event bubbling)

    This event will likely be used together with the focusin event

    Example 1 Watch for a loss of focus to occur inside paragraphs and note the dif ferencebetween the focusout count and the blur count

    CSS

    inputs float left margin-right 1em

    inputs p margin-top 0

    Javascript

    var fo = 0 b = 0$(p)focusout(function() fo++ $(fo) text(focusout fired + fo + x))blur(function() b++ $(b) text(blur fired + b + x) )

    HTML

    ltdiv class=inputsgt ltpgt ltinput type=text gtltbr gt ltinput type=text gt ltpgt ltpgt ltinput type=password gt ltpgtltdivgtltdiv id=fogtfocusout fireltdivgtltdiv id=bgtblur fireltdivgt

    focusin

    Bind an event handler to the focusin JavaScript event

    Added in version 143

    focusin(eventData handler(eventObject))jQuery

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

    This method is a shortcut for bind(focusin handler)

    The focusin event is sent to an element when it or any element inside of it gains focus This isdist inct f rom the focus event in that it supports detect ing the focus event on parent elements(in other words it supports event bubbling)

    This event will likely be used together with the focusout event

    Example 1 Watch for a focus to occur within the paragraphs on the page

    CSS

    span displaynone

    Javascript

    $(p)focusin(function() $(this)find(span)css(display inl ine)fadeOut(1000) )

    HTML

    ltpgtltinput type=text gt ltspangtfocusin fireltspangtltpgtltpgtltinput type=password gt ltspangtfocusin fireltspangtltpgt

    eventisImmediatePropagationStopped

    Returns whether eventstopImmediatePropagat ion() was ever called on this event object

    Added in version 13

    eventisImmediatePropagat ionStopped()Boolean

    This property was introduced in DOM level 3

    Example 1 Checks whether eventstopImmediatePropagat ion() was called

    Javascript

    function immediatePropStopped(e) var msg = i f ( eisImmediatePropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

    $(button)cl ick(function(event) immediatePropStopped(event) eventstopImmediatePropagation() immediatePropStopped(event))

    HTML

    ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

    eventstopImmediatePropagation

    Keeps the rest of the handlers f rom being executed and prevents the event f rom bubbling upthe DOM tree

    Added in version 13

    eventstopImmediatePropagat ion()

    In addit ion to keeping any addit ional handlers on an element f rom being executed this methodalso stops the bubbling by implicit ly calling eventstopPropagat ion() To simply prevent theevent f rom bubbling to ancestor elements but allow other event handlers to execute on thesame element we can use eventstopPropagat ion() instead

    Use eventisImmediatePropagat ionStopped() to know whether this method was ever called (onthat event object)

    Example 1 Prevents other event handlers f rom being called

    CSS

    p height 30px width 150px background-color ccf div height 30px width 150px background-color cfc

    Javascript

    $(p)cl ick(function(event) eventstopImmediatePropagation())$(p)cl ick(function(event) This function wont be executed $(this)css(background-color f00)) $(div)cl ick(function(event) This function wil l be executed $(this)css(background-color f00))

    HTML

    ltpgtparagraphltpgtltdivgtdivisionltdivgt

    eventisPropagationStopped

    Returns whether eventstopPropagat ion() was ever called on this event object

    Added in version 13

    eventisPropagat ionStopped()Boolean

    This event method is described in the W3C DOM Level 3 specif icat ion

    Example 1 Checks whether eventstopPropagat ion() was called

    Javascript

    function propStopped(e) var msg = i f ( eisPropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

    $(button)cl ick(function(event) propStopped(event) eventstopPropagation() propStopped(event))

    HTML

    ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

    eventstopPropagation

    Prevents the event f rom bubbling up the DOM tree prevent ing any parent handlers f rom beingnot if ied of the event

    Added in version 10

    eventstopPropagat ion()

    We can use eventisPropagat ionStopped() to determine if this method was ever called (on thatevent object)

    This method works for custom events t riggered with t rigger() as well

    Note that this will not prevent other handlers on the same element f rom running

    Example 1 Kill the bubbling on the click event

    Javascript

    $(p)cl ick(function(event) eventstopPropagation() do something)

    eventisDefaultPrevented

    Returns whether eventpreventDefault () was ever called on this event object

    Added in version 13

    eventisDefaultPrevented()Boolean

    Example 1 Checks whether eventpreventDefault () was called

    Javascript

    $(a)cl ick(function(event) alert( eventisDefaultPrevented() ) false eventpreventDefault() alert( eventisDefaultPrevented() ) true)

    eventpreventDefault

    If this method is called the default act ion of the event will not be triggered

    Added in version 10

    eventpreventDefault ()undef ined

    For example clicked anchors will not take the browser to a new URL We can useeventisDefaultPrevented() to determine if this method has been called by an event handlerthat was triggered by this event

    Example 1 Cancel the default act ion (navigat ion) of the click

    Javascript

    $(a)cl ick(function(event) eventpreventDefault() $(ltdivgt) append(default + eventtype + prevented) appendTo(log))

    HTML

    lta href=httpjquerycomgtdefault cl ick action is preventedltagtltdiv id=loggtltdivgt

    eventtimeStamp

    The dif ference in milliseconds between the t ime an event is t riggered and January 1 1970

    Added in version 126

    This property can be useful for prof iling the performance of certain jQuery funct ions by gett ingthe eventt imeStamp value at two points in the code and not ing the dif ference

    Example 1 Display the t ime since the click handler last executed

    CSS

    div height 100px width 300px margin 10px background-color ffd overflow auto

    Javascript

    var last diff$(div)cl ick(function(event) if ( last ) diff = eventtimeStamp - last $(div)append(time since last event + diff + ltbrgt) else $(div)append(Click againltbrgt) last = eventtimeStamp)

    HTML

    ltdivgtClickltdivgt

    eventresult

    The last value returned by an event handler that was triggered by this event unless the valuewas undef ined

    Added in version 13

    This property can be useful for gett ing previous return values of custom events

    Example 1 Display previous handlers return value

    Javascript

    $(button)cl ick(function(event) return hey)$(button)cl ick(function(event) $(p)html( eventresult ))

    HTML

    ltbuttongtdisplay eventresultltbuttongtltpgtltpgt

    eventwhich

    For key or button events this at t ribute indicates the specif ic button or key that was pressed

    Added in version 113

    eventwhich normalizes eventkeyCode and eventcharCode It is recommended to watcheventwhich for keyboard key input For more detail read about eventcharCode on the MDC

    Example 1 Log what key was depressed

    Javascript

    $(whichkey)bind(keydownfunction(e) $(log)html(etype + + ewhich ))

    HTML

    ltinput id=whichkey value=type somethinggtltdiv id=loggtltdivgt

    Results

    keydown 74

    eventpageY

    The mouse posit ion relat ive to the top edge of the document

    Added in version 104

    Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthis if rame)

    CSS

    body background-color eef div padding 20px

    HTML

    ltdiv id=loggtltdivgt

    Javascript

    $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

    eventpageX

    The mouse posit ion relat ive to the lef t edge of the document

    Added in version 104

    Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthe if rame)

    CSS

    body background-color eef div padding 20px

    HTML

    ltdiv id=loggtltdivgt

    Javascript

    $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

    eventcurrentTarget

    The current DOM element within the event bubbling phase

    Added in version 13

    This property will typically be equal to the this of the funct ion

    If you are using jQueryproxy or another form of scope manipulation this will be equal towhatever context you have provided not eventcurrentTarget

    Example 1 Alert that currentTarget matches the `this` keyword

    Javascript

    $(p)cl ick(function(event) alert( eventcurrentTarget === this ) true)

    eventrelatedTarget

    The other DOM element involved in the event if any

    Added in version 114

    For mouseout indicates the element being entered for mouseover indicates the elementbeing exited

    Example 1 On mouseout of anchors alert the element type being entered

    Javascript

    $(a)mouseout(function(event) alert(eventrelatedTargetnodeName) DIV)

    eventdata

    The opt ional data passed to jQueryfnbind when the current execut ing handler was bound

    Added in version 11

    Example 1 The descript ion of the example

    Javascript

    $(a)each(function(i) $(this)bind(cl ick indexi function(e) alert(my index is + edataindex) ))

    eventtarget

    The DOM element that init iated the event

    Added in version 10

    The target property can be the element that registered for the event or a descendant of it It isof ten useful to compare eventtarget to this in order to determine if the event is being handleddue to event bubbling This property is very useful in event delegat ion when events bubble

    Example 1 Display the tags name on click

    Javascript

    $(body)cl ick(function(event) $(log)html(clicked + eventtargetnodeName))

    CSS

    span strong p padding 8px display block border 1px solid 999

    HTML

    ltdiv id=loggtltdivgtltdivgt ltpgt ltstronggtltspangtclickltspangtltstronggt ltpgtltdivgt

    Example 2 Implements a simple event delegat ion The click handler is added to an unorderedlist and the children of its li children are hidden Clicking one of the li children toggles (seetoggle()) their children

    Javascript

    function handler(event) var $target = $(eventtarget) i f( $targetis( l i) ) $targetchildren()toggle() $(ul)cl ick(handler)find(ul)hide()

    HTML

    ltulgt ltligtitem 1 ltulgt ltligtsub item 1-altligt ltligtsub item 1-bltligt ltulgt ltl igt ltligtitem 2 ltulgt ltligtsub item 2-altligt ltligtsub item 2-bltligt ltulgt ltl igt ltulgt

    eventtype

    Describes the nature of the event

    Added in version 10

    Example 1 On all anchor clicks alert the event type

    Javascript

    $(a)cl ick(function(event) alert(eventtype) cl ick)

    keydown

    Bind an event handler to the keydown JavaScript event or t rigger that event on an element

    Added in version 10

    keydown()jQuery

    This method is a shortcut for bind(keydown handler) in the f irst and second variat ions and

    t rigger(keydown) in the third

    The keydown event is sent to an element when the user f irst presses a key on the keyboard Itcan be at tached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

    For example consider the HTML

    ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the input f ield

    $(target)keydown(function() alert(Handler for keydown() called))

    Now when the insert ion point is inside the f ield pressing a key displays the alert

    Handler for keydown() called

    To trigger the event manually apply keydown() without an argument

    $(other)cl ick(function() $(target)keydown())

    After this code executes clicks on Trigger the handler will also alert the message

    If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

    To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

    Example 1 Show the event object for the keydown handler when a key is pressed in the input

    Javascript

    var xTriggered = 0$(target)keydown(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keydown() called + xTriggered + time(s) $print(msg html) $print(event))

    $(other)cl ick(function() $(target)keydown())

    CSS

    fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

    HTML

    ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

    scroll

    Bind an event handler to the scroll JavaScript event or t rigger that event on an element

    Added in version 10

    scroll()jQuery

    This method is a shortcut for bind(scroll handler) in the f irst and second variat ions andtrigger(scroll) in the third

    The scroll event is sent to an element when the user scrolls to a dif ferent place in the elementIt applies to window objects but also to scrollable f rames and elements with the overf low CSSproperty set to scroll (or auto when the element s explicit height or width is less than the heightor width of its contents)

    For example consider the HTML

    ltdiv id=target style=overflow scroll width 200px height 100pxgt 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 al iquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt moll it anim id est laborumltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The style def init ion is present to make the target element small enough to be scrollable

    The scroll event handler can bebound to this element

    $(target)scroll(function() $(log)append(ltdivgtHandler for scroll() calledltdivgt))

    Now when the user scrolls the text up or down one or more messages are appended to ltdiv

    id=loggtltdivgt

    Handler for scroll() called

    To trigger the event manually apply scroll() without an argument

    $(other)cl ick(function() $(target)scroll())

    After this code executes clicks on Trigger the handler will also append the message

    A scroll event is sent whenever the element s scroll posit ion changes regardless of the causeA mouse click or drag on the scroll bar dragging inside the element pressing the arrow keys orusing the mouses scroll wheel could cause this event

    Example 1 To do something when your page is scrolled

    Javascript

    $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(window)scroll(function () $(span)css(display inl ine)fadeOut(slow) )

    CSS

    div colorblue p colorgreen span colorred displaynone

    HTML

    ltdivgtTry scroll ing the iframeltdivgt ltpgtParagraph - ltspangtScroll happenedltspangtltpgt

    resize

    Bind an event handler to the resize JavaScript event or t rigger that event on an element

    Added in version 10

    resize()jQuery

    This method is a shortcut for bind(resize handler) in the f irst and second variat ions andtrigger(resize) in the third

    The resize event is sent to the window element when the size of the browser window changes

    $(window)resize(function() $(log)append(ltdivgtHandler for resize() calledltdivgt))

    Now whenever the browser windows size is changed the message is appended to ltdivid=loggt one or more t imes depending on the browser

    Code in a resize handler should never rely on the number of t imes the handler is calledDepending on implementat ion resize events can be sent cont inuously as the resizing is inprogress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safariand Chrome) or only once at the end of the resize operat ion (the typical behavior in someother browsers such as Opera)

    Example 1 To see the window width while (or af ter) it is resized t ry

    Javascript

    $(window)resize(function() $(body)prepend(ltdivgt + $(window)width() + ltdivgt))

    keyup

    Bind an event handler to the keyup JavaScript event or t rigger that event on an element

    Added in version 10

    keyup()jQuery

    This method is a shortcut for bind(keyup handler) in the f irst two variat ions andtrigger(keyup) in the third

    The keyup event is sent to an element when the user releases a key on the keyboard It can beattached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

    For example consider the HTML

    ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the input f ield

    $(target)keyup(function() alert(Handler for keyup() called))

    Now when the insert ion point is inside the f ield and a key is pressed and released the alert isdisplayed

    Handler for keyup() called

    To trigger the event manually apply keyup() without arguments

    $(other)cl ick(function() $(target)keyup())

    After this code executes clicks on Trigger the handler will also alert the message

    If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

    To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

    Example 1 Show the event object for the keyup handler when a key is released in the input

    Javascript

    var xTriggered = 0$(target)keyup(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keyup() called + xTriggered + time(s) $print(msg html) $print(event))

    $(other)cl ick(function() $(target)keyup())

    CSS

    fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

    HTML

    ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

    keypress

    Bind an event handler to the keypress JavaScript event or t rigger that event on an element

    Added in version 10

    keypress()jQuery

    Note as the keypress event isnt covered by any of f icial specif icat ion the actual behaviorencountered when using it may dif fer across browsers browser versions and plat forms

    This method is a shortcut for bind(keypress handler) in the f irst two variat ions andtrigger(keypress) in the third

    The keypress event is sent to an element when the browser registers keyboard input This issimilar to the keydown event except in the case of key repeats If the user presses and holds akey a keydown event is t riggered once but separate keypress events are t riggered for eachinserted character In addit ion modif ier keys (such as Shif t ) t rigger keydown events but notkeypress events

    A keypress event handler can be at tached to any element but the event is only sent to theelement that has the focus Focusable elements can vary between browsers but formelements can always get focus so are reasonable candidates for this event type

    For example consider the HTML

    ltformgt ltfieldsetgt ltinput id=target type=text value=Hello there gt ltfieldsetgtltformgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be bound to the input f ield

    $(target)keypress(function() alert(Handler for keypress() called))

    Now when the insert ion point is inside the f ield pressing a key displays the alert

    Handler for keypress() called

    The message repeats if the key is held down To trigger the event manually apply keypress()without an argument

    $(other)cl ick(function() $(target)keypress())

    After this code executes clicks on Trigger the handler will also alert the message

    If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

    To determine which character was entered examine the event object that is passed to thehandler funct ion While browsers use dif fering propert ies to store this informat ion jQuerynormalizes the which property so you can reliably use it to retrieve the character code

    Note that keydown and keyup provide a code indicat ing which key is pressed while keypressindicates which character was entered For example a lowercase a will be reported as 65 bykeydown and keyup but as 97 by keypress An uppercase A is reported as 65 by all eventsBecause of this dist inct ion when catching special keystrokes such as arrow keys keydown() orkeyup() is a better choice

    Example 1 Show the event object when a key is pressed in the input Note This demo relies ona simple $print() plugin (ht tpapijquerycomscriptseventsjs) for the event object s output

    Javascript

    var xTriggered = 0$(target)keypress(function(event) if ( eventwhich == 13 ) eventpreventDefault() xTriggered++ var msg = Handler for keypress() called + xTriggered + time(s) $print( msg html ) $print( event ))

    $(other)cl ick(function() $(target)keypress())

    CSS

    fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

    HTML

    ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript src=httpapijquerycomscriptseventsjsgtltscriptgt

    submit see Forms

    select see Forms

    change see Forms

    blur see Forms

    focus see Forms

    mousemove

    Bind an event handler to the mousemove JavaScript event or t rigger that event on anelement

    Added in version 10

    mousemove()jQuery

    This method is a shortcut for bind(mousemove handler) in the f irst two variat ions andtrigger(mousemove) in the third

    The mousemove event is sent to an element when the mouse pointer moves inside theelement Any HTML element can receive this event

    For example consider the HTML

    ltdiv id=targetgt Move hereltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The event handler can be bound to the target

    $(target)mousemove(function(event) var msg = Handler for mousemove() called at msg += eventpageX + + eventpageY $(log)append(ltdivgt + msg + ltdivgt))

    Now when the mouse pointer moves within the target button the messages are appended toltdiv id=loggt

    Handler for mousemove() called at (399 48)

    Handler for mousemove() called at (398 46)

    Handler for mousemove() called at (397 44)

    Handler for mousemove() called at (396 42)

    To trigger the event manually apply mousemove() without an argument

    $(other)cl ick(function() $(target)mousemove())

    After this code executes clicks on the Trigger button will also append the message

    Handler for mousemove() called at (undef ined undef ined)

    When tracking mouse movement you usually need to know the actual posit ion of the mousepointer The event object that is passed to the handler contains some informat ion about themouse coordinates Propert ies such as clientX of fsetX and pageX are available but supportfor them dif fers between browsers Fortunately jQuery normalizes the pageX and pageYpropert ies so that they can be used in all browsers These propert ies provide the X and Ycoordinates of the mouse pointer relat ive to the top-lef t corner of the document as illustratedin the example output above

    Keep in mind that the mousemove event is t riggered whenever the mouse pointer moves evenfor a pixel This means that hundreds of events can be generated over a very small amount oft ime If the handler has to do any signif icant processing or if mult iple handlers for the eventexist this can be a serious performance drain on the browser It is important therefore toopt imize mousemove handlers as much as possible and to unbind them as soon as they areno longer needed

    A common pattern is to bind the mousemove handler f rom within a mousedown hander and tounbind it f rom a corresponding mouseup handler If implement ing this sequence of eventsremember that the mouseup event might be sent to a dif ferent HTML element than themousemove event was To account for this the mouseup handler should typically be bound toan element high up in the DOM tree such as ltbodygt

    Example 1 Show the mouse coordinates when the mouse is moved over the yellow divCoordinates are relat ive to the window which in this case is the if rame

    Javascript

    $(div)mousemove(function(e) var pageCoords = ( + epageX + + epageY + ) var cl ientCoords = ( + ecl ientX + + ecl ientY + ) $(spanfirst)text(( epageX epageY ) - + pageCoords) $(spanlast)text(( ecl ientX ecl ientY ) - + clientCoords) )

    CSS

    div width220px height170px margin10px margin-right50px backgroundyellow border2px groove floatright p margin0 margin-left10px colorred width220px height120px padding-top70px floatleft font-size14px span displayblock

    HTML

    ltpgt Try scroll ing too ltspangtMove the mouse over the divltspangt ltspangtampnbspltspangt ltpgt

    ltdivgtltdivgt

    hover

    Bind two handlers to the matched elements to be executed when the mouse pointer entersand leaves the elements

    Added in version 10

    hover(handlerIn(eventObject) handlerOut(eventObject))jQuery

    handlerIn(eventObject)Funct ion A funct ion to execute when the mouse pointerenters the element

    handlerOut(eventObject)Funct ion A funct ion to execute when the mouse pointerleaves the element

    The hover() method binds handlers for both mouseenter and mouseleave events You can useit to simply apply behavior to an element during the t ime the mouse is within the element

    Calling $(selector)hover(handlerIn handlerOut) is shorthand for

    $(selector)mouseenter(handlerIn)mouseleave(handlerOut)

    See the discussions for mouseenter() and mouseleave() for more details

    Example 1 To add a special style to list items that are being hovered over t ry

    Javascript

    $(l i)hover( function () $(this)append($(ltspangt ltspangt)) function () $(this)find(spanlast)remove() )

    l i with fade class$(l i fade)hover(function()$(this)fadeOut(100)$(this)fadeIn(500))

    CSS

    ul margin-left20px colorblue l i cursordefault span colorred

    HTML

    ltulgt ltligtMilkltligt ltligtBreadltligt ltli class=fadegtChipsltligt

    ltli class=fadegtSocksltligt ltulgt

    Example 2 To add a special style to table cells that are being hovered over t ry

    Javascript

    $(td)hover( function () $(this)addClass(hover) function () $(this)removeClass(hover) )

    Example 3 To unbind the above example use

    Javascript

    $(td)unbind(mouseenter mouseleave)

    hover

    Bind a single handler to the matched elements to be executed when the mouse pointer entersor leaves the elements

    Added in version 14

    hover(handlerInOut(eventObject))jQuery

    handlerInOut(eventObject)Funct ion A funct ion to execute when the mouse pointerenters or leaves the element

    The hover() method when passed a single funct ion will execute that handler for bothmouseenter and mouseleave events This allows the user to use jQuerys various togglemethods within the handler or to respond dif ferent ly within the handler depending on theeventtype

    Calling $(selector)hover(handlerInOut) is shorthand for

    $(selector)bind(mouseenter mouseleave handlerInOut)

    See the discussions for mouseenter() and mouseleave() for more details

    Example 1 Slide the next sibling LI up or down on hover and toggle a class

    Javascript

    $(l i)fi lter(odd)hide() end()fi lter(even)hover( function () $(this)toggleClass(active) next()stop(true true)sl ideToggle() )

    CSS

    ul margin-left20px colorblue l i cursordefault l i active backgroundblackcolorwhite span colorred

    HTML

    ltulgt ltligtMilkltligt ltligtWhiteltligt ltligtCarrotsltligt ltligtOrangeltligt ltligtBroccoliltl igt ltligtGreenltligt ltulgt

    mouseleave

    Bind an event handler to be f ired when the mouse leaves an element or t rigger that handler onan element

    Added in version 10

    mouseleave()jQuery

    This method is a shortcut for bind(mouseleave handler) in the f irst two variat ions andtrigger(mouseleave) in the third

    The mouseleave JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer leaves the element Any HTML elementcan receive this event

    For example consider the HTML

    ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The event handler can be boundto any element

    $(outer)mouseleave(function() $(log)append(ltdivgtHandler for mouseleave() calledltdivgt))

    Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

    $(other)cl ick(function() $(outer)mouseleave())

    After this code executes clicks on Trigger the handler will also append the message

    The mouseleave event dif fers f rom mouseout in the way it handles event bubbling If mouseoutwere used in this example then when the mouse pointer moved out of the Inner element thehandler would be triggered This is usually undesirable behavior The mouseleave event on theother hand only t riggers its handler when the mouse leaves the element it is bound to not adescendant So in this example the handler is t riggered when the mouse leaves the Outerelement but not the Inner element

    Example 1 Show number of t imes mouseout and mouseleave events are t riggered mouseoutf ires when the pointer moves out of child element as well while mouseleave f ires only when thepointer moves out of the bound element

    CSS

    divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

    Javascript

    var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) )mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )

    var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) )mouseleave(function() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

    HTML

    ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    mouseenter

    Bind an event handler to be f ired when the mouse enters an element or t rigger that handler onan element

    Added in version 10

    mouseenter()jQuery

    This method is a shortcut for bind(mouseenter handler) in the f irst two variat ions andtrigger(mouseenter) in the third

    The mouseenter JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer enters the element Any HTML elementcan receive this event

    For example consider the HTML

    ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The event handler can be boundto any element

    $(outer)mouseenter(function() $(log)append(ltdivgtHandler for mouseenter() calledltdivgt))

    Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

    $(other)cl ick(function() $(outer)mouseenter())

    After this code executes clicks on Trigger the handler will also append the message

    The mouseenter event dif fers f rom mouseover in the way it handles event bubbling Ifmouseover were used in this example then when the mouse pointer moved over the Innerelement the handler would be triggered This is usually undesirable behavior The mouseenterevent on the other hand only t riggers its handler when the mouse enters the element it isbound to not a descendant So in this example the handler is t riggered when the mouse entersthe Outer element but not the Inner element

    Example 1 Show texts when mouseenter and mouseout event t riggering mouseover f ireswhen the pointer moves into the child element as well while mouseenter f ires only when thepointer moves into the bound element

    CSS

    divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

    Javascript

    var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) $(plastthis)text(++i) )mouseout(function() $(pfirstthis)text(mouse out) )

    var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) $(plastthis)text(++n) )mouseleave(function() $(pfirstthis)text(mouse leave) )

    HTML

    ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    mouseout

    Bind an event handler to the mouseout JavaScript event or t rigger that event on an element

    Added in version 10

    mouseout()jQuery

    This method is a shortcut for bind(mouseout handler) in the f irst two variat ion andtrigger(mouseout ) in the third

    The mouseout event is sent to an element when the mouse pointer leaves the element AnyHTML element can receive this event

    For example consider the HTML

    ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The event handler can be boundto any element

    $(outer)mouseout(function() $(log)append(Handler for mouseout() called))

    Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt To trigger the event manually apply mouseout() without an argument

    $(other)cl ick(function() $(outer)mouseout())

    After this code executes clicks on Trigger the handler will also append the message

    This event type can cause many headaches due to event bubbling For instance when themouse pointer moves out of the Inner element in this example a mouseout event will be sentto that then trickle up to Outer This can trigger the bound mouseout handler at inopportunet imes See the discussion for mouseleave() for a useful alternat ive

    Example 1 Show the number of t imes mouseout and mouseleave events are t riggeredmouseout f ires when the pointer moves out of the child element as well while mouseleave f iresonly when the pointer moves out of the bound element

    CSS

    divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

    Javascript

    var i = 0 $(divoverout)mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )mouseover(function() $(pfirstthis)text(mouse over) )

    var n = 0 $(diventerleave)bind(mouseenterfunction() $(pfirstthis)text(mouse enter) )bind(mouseleavefunction() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

    HTML

    ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

    mouseover

    Bind an event handler to the mouseover JavaScript event or t rigger that event on anelement

    Added in version 10

    mouseover()jQuery

    This method is a shortcut for bind(mouseover handler) in the f irst two variat ions andtrigger(mouseover) in the third

    The mouseover event is sent to an element when the mouse pointer enters the element AnyHTML element can receive this event

    For example consider the HTML

    ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

    The event handler can be boundto any element

    $(outer)mouseover(function() $(log)append(ltdivgtHandler for mouseover() calledltdivgt))

    Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt We can also t rigger the event when another element is clicked

    $(other)cl ick(function() $(outer)mouseover())

    After this code executes clicks on Trigger the handler will also append the message

    This event type can cause many headaches due to event bubbling For instance when themouse pointer moves over the Inner element in this example a mouseover event will be sent tothat then trickle up to Outer This can trigger our bound mouseover handler at inopportunet imes See the discussion for mouseenter() for a useful alternat ive

    Example 1 Show the number of t imes mouseover and mouseenter events are t riggeredmouseover f ires when the pointer moves into the child element as well while mouseenter f iresonly when the pointer moves into the bound element

    CSS

    divout width40 height120px margin0 15px background-colorD6EDFC floatleft divin width60 height60 background-colorFFCC00 margin10px auto p l ine-height1em margin0 padding0

    Javascript

    var i = 0 $(divoverout)mouseover(function() i += 1 $(this)find(span)text( mouse over x + i ) )mouseout(function() $(this)find(span)text(mouse out ) )

    var n = 0 $(diventerleave)mouseenter(function() n += 1 $(this)find(span)text( mouse enter x + n ) )mouseleave(function() $(this)find(span)text(mouse leave) )

    HTML

    ltdiv class=out overoutgt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

    ltdiv class=out enterleavegt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

    dblclick

    Bind an event handler to the dblclick JavaScript event or t rigger that event on an element

    Added in version 10

    dblclick()jQuery

    This method is a shortcut for bind(dblclick handler) in the f irst two variat ions andtrigger(dblclick) in the third The dblclick event is sent to an element when the element isdouble-clicked Any HTML element can receive this event For example consider the HTML

    ltdiv id=targetgt Double-click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be boundto any ltdivgt

    $(target)dblcl ick(function() alert(Handler for dblcl ick() called))

    Now double-clicking on this element displays the alert

    Handler for dblclick() called

    To trigger the event manually apply dblclick() without an argument

    $(other)cl ick(function() $(target)dblcl ick())

    After this code executes (single) clicks on Trigger the handler will also alert the message

    The dblclick event is only t riggered af ter this exact series of events

    The mouse button is depressed while the pointer is inside the element

    The mouse button is released while the pointer is inside the element

    The mouse button is depressed again while the pointer is inside the element within at ime window that is system-dependent

    The mouse button is released while the pointer is inside the element

    It is inadvisable to bind handlers to both the click and dblclick events for the same element Thesequence of events t riggered varies f rom browser to browser with some receiving two clickevents before the dblclick and others only one Double-click sensit ivity (maximum t ime betweenclicks that is detected as a double click) can vary by operat ing system and browser and is of tenuser-conf igurable

    Example 1 To bind a Hello World alert box the dblclick event on every paragraph on the page

    Javascript

    $(p)dblcl ick( function () alert(Hello World) )

    Example 2 Double click to toggle background color

    Javascript

    var divdbl = $(divfirst) divdbldblcl ick(function () divdbltoggleClass(dbl) )

    CSS

    div backgroundblue colorwhite height100px width150px divdbl backgroundyellowcolorblack

    HTML

    ltdivgtltdivgtltspangtDouble cl ick the blockltspangt

    click

    Bind an event handler to the click JavaScript event or t rigger that event on an element

    Added in version 10

    click()jQuery

    This method is a shortcut for bind(click handler) in the f irst two variat ions and t rigger(click)in the third

    The click event is sent to an element when the mouse pointer is over the element and themouse button is pressed and released Any HTML element can receive this event

    For example consider the HTMLltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be boundto any ltdivgt

    $(target)cl ick(function() alert(Handler for cl ick() called))

    Now if we click on this element the alert is displayed

    Handler for click() called

    We can also t rigger the event when a dif ferent element is clicked

    $(other)cl ick(function() $(target)cl ick())

    After this code executes clicks on Trigger the handler will also alert the message

    The click event is only t riggered af ter this exact series of events

    The mouse button is depressed while the pointer is inside the element

    The mouse button is released while the pointer is inside the element

    This is usually the desired sequence before taking an act ion If this is not required themousedown or mouseup event may be more suitable

    Example 1 To hide paragraphs on a page when they are clicked

    Javascript

    $(p)cl ick(function () $(this)sl ideUp() ) $(p)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

    CSS

    p colorred margin5px cursorpointer phil ite backgroundyellow

    HTML

    ltpgtFirst Paragraphltpgt

    ltpgtSecond Paragraphltpgt ltpgtYet one more Paragraphltpgt

    Example 2 To trigger the click event on all of the paragraphs on the page

    Javascript

    $(p)cl ick()

    mouseup

    Bind an event handler to the mouseup JavaScript event or t rigger that event on an element

    Added in version 10

    mouseup()jQuery

    This method is a shortcut for bind(mouseup handler) in the f irst variat ion andtrigger(mouseup) in the second

    The mouseup event is sent to an element when the mouse pointer is over the element and themouse button is released Any HTML element can receive this event

    For example consider the HTML

    ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be boundto any ltdivgt

    $(target)mouseup(function() alert(Handler for mouseup() called))

    Now if we click on this element the alert is displayed

    Handler for mouseup() called

    We can also t rigger the event when a dif ferent element is clicked

    $(other)cl ick(function() $(target)mouseup())

    After this code executes clicks on Trigger the handler will also alert the message

    If the user clicks outside an element drags onto it and releases the button this is st ill countedas a mouseup event This sequence of act ions is not t reated as a button press in most userinterfaces so it is usually better to use the click event unless we know that the mouseup eventis preferable for a part icular situat ion

    Example 1 Show texts when mouseup and mousedown event t riggering

    Javascript

    $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

    HTML

    ltpgtPress mouse and release hereltpgt

    mousedown

    Bind an event handler to the mousedown JavaScript event or t rigger that event on anelement

    Added in version 10

    mousedown()jQuery

    This method is a shortcut for bind(mousedown handler) in the f irst variat ion andtrigger(mousedown) in the second

    The mousedown event is sent to an element when the mouse pointer is over the element andthe mouse button is pressed Any HTML element can receive this event

    For example consider the HTML

    ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

    The event handler can be boundto any ltdivgt

    $(target)mousedown(function() alert(Handler for mousedown() called))

    Now if we click on this element the alert is displayed

    Handler for mousedown() called

    We can also t rigger the event when a dif ferent element is clicked

    $(other)cl ick(function() $(target)mousedown())

    After this code executes clicks on Trigger the handler will also alert the message

    The mousedown event is sent when any mouse button is clicked To act only on specif icbuttons we can use the event object s which property Not all browsers support this property(Internet Explorer uses button instead) but jQuery normalizes the property so that it is safe touse in any browser The value of which will be 1 for the lef t but ton 2 for the middle button or 3for the right button

    This event is primarily useful for ensuring that the primary button was used to begin a dragoperat ion if ignored strange results can occur when the user at tempts to use a context menuWhile the middle and right buttons can be detected with these propert ies this is not reliable InOpera 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 st ill countedas a mousedown event This sequence of act ions is t reated as a canceling of the buttonpress in most user interfaces so it is usually better to use the click event unless we know thatthe mousedown event is preferable for a part icular situat ion

    Example 1 Show texts when mouseup and mousedown event t riggering

    Javascript

    $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

    HTML

    ltpgtPress mouse and release hereltpgt

    error

    Bind an event handler to the error JavaScript event

    Added in version 143

    error(eventData handler(eventObject))jQuery

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

    This method is a shortcut for bind(error handler)

    The error event is sent to elements such as images that are referenced by a document andloaded by the browser It is called if the element was not loaded correct ly

    For example consider a page with a simple image element

    ltimg alt=Book id=book gt

    The event handler can be bound to the image

    $(book) error(function() alert(Handler for error() called) ) attr(src missingpng)

    If the image cannot be loaded (for example because it is not present at the supplied URL) thealert is displayed

    Handler for error() called

    The event handler must be attached before the browser fires the error eventwhich is why the example sets the src attribute after attaching the handler Alsothe error event may not be correctly fired when the page is served locally errorrelies on HTTP status codes and will generally not be triggered if the URL usesthe file protocol

    Note A jQuery error event handler should not be at tached to the window object The browserf ires the windows error event when a script error occurs However the window error eventreceives dif ferent arguments and has dif ferent return value requirements than convent ionalevent handlers Use windowonerror instead

    Example 1 To hide the broken image icons for IE users you can try

    Javascript

    $(img) error(function() $(this)hide() ) attr(src missingpng)

    unload

    Bind an event handler to the unload JavaScript event

    Added in version 143

    unload(eventData handler(eventObject))jQuery

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

    This method is a shortcut for bind(unload handler)

    The unload event is sent to the window element when the user navigates away from the pageThis 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 t rigger the eventClosing the browser window will cause the event to be triggered Even a page reload will f irstcreate an unload event

    The exact handling of the unload event has varied from version to version ofbrowsers For example some versions of Firefox trigger the event when a link isfollowed but not when the window is closed In practical usage behavior shouldbe tested on all supported browsers and contrasted with the proprietarybeforeunload event

    Any unload event handler should be bound to the window object

    $(window)unload(function() alert(Handler for unload() called))

    After this code executes the alert will be displayed whenever the browser leaves the currentpage It is not possible to cancel the unload event with preventDefault () This event is availableso that scripts can perform cleanup when the user leaves the page

    Example 1 To display an alert when a page is unloaded

    Javascript

    $(window)unload( function () alert(Bye now) )

    load

    Bind an event handler to the load JavaScript event

    Added in version 143

    load(eventData handler(eventObject))jQuery

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

    This method is a shortcut for bind(load handler)

    The load 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 f ramesif rames and the window object

    For example consider a page with a simple image

    ltimg src=bookpng alt=Book id=book gt

    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 executedearlier it is usually best to place it in a handler sent to the ready() method

    The Ajax module also has a method named load() Which one is fired dependson the set of arguments passed

    Caveats of the load event when used with images

    A common challenge developers attempt to solve using the load() shortcut is toexecute a function when an image (or collection of images) have completelyloaded There are several known caveats with this that should be noted Theseare

    It doesnt work consistently nor reliably cross-browser

    It doesnt fire correctly in WebKit if the image src is set to the same src asbefore

    It doesnt correctly bubble up the DOM tree

    Can cease to fire for images that already live in the browsers cache

    Note The live() and delegate() methods cannot be used to detect the load eventof an iframe The load event does not correctly bubble up the parent documentand the eventtarget isnt set by Firefox IE9 or Chrome which is required to doevent delegation

    Note When calling load() using a URL without a suffixed selector expression the

    content is passed to html() prior to scripts being removed This executes the scriptblocks before they are discarded If load() is however called with a selectorexpression appended to the URL the scripts are stripped out prior to the DOMbeing updated which is why they are never executed An example of both casescan be seen below

    Here any JavaScript loaded into a as a part of the document will successfully execute

    $(a)load(articlehtml)

    However in this case script blocks in the document being loaded into b are stripped out priorto being executed

    $(b)load(articlehtml target)

    Example 1 Run a funct ion when the page is fully loaded including graphics

    Javascript

    $(window)load(function () run code)

    Example 2 Add the class bigImg to all images with height greater then 100 upon each imageload

    Javascript

    $( imguserIcon)load(function() if($(this)height() gt 100) $(this)addClass(bigImg) )

    ready

    Specify a funct ion to execute when the DOM is fully loaded

    Added in version 10

    ready(handler)jQuery

    handlerFunct ion A funct ion to execute af ter the DOM is ready

    While JavaScript provides the load event for execut ing code when a page is rendered thisevent does not get t riggered unt il all assets such as images have been completely received Inmost cases the script can be run as soon as the DOM hierarchy has been fully constructedThe handler passed to ready() is guaranteed to be executed af ter the DOM is ready so this isusually the best place to at tach all other event handlers and run other jQuery code When usingscripts that rely on the value of CSS style propert ies it s important to reference externalstylesheets or embed style elements before referencing the scripts

    In cases where code relies on loaded assets (for example if the dimensions of an image arerequired) the code should be placed in a handler for the load event instead

    The ready() method is generally incompatible with the ltbody onload=gtattribute If load must be used either do not use ready() or use jQuerys load()method to attach load event handlers to the window or to more specific items likeimages

    All three of the following syntaxes are equivalent

    $(document)ready(handler)

    $()ready(handler) (this is not recommended)

    $(handler)

    There is also $(document)bind(ready handler) This behaves similarly to the ready methodbut with one except ion If the ready event has already f ired and you try to bind(ready) thebound handler will not be executed Ready handlers bound this way are executed after anybound by the other three methods above

    The ready() method can only be called on a jQuery object matching the current document sothe selector can be omit ted

    The ready() method is typically used with an anonymous funct ion

    $(document)ready(function() Handler for ready() called)

    Which is equivalent to calling

    $(function() Handler for ready() called)

    If ready() is called af ter the DOM has been init ialized the new handler passed in will beexecuted immediately

    Aliasing the jQuery Namespace

    When using another JavaScript library we may wish to call $noConf lict () to avoid namespacedif f icult ies When this funct ion is called the $ shortcut is no longer available forcing us to writejQuery each t ime we would normally write $ However the handler passed to the ready()method can take an argument which is passed the global jQuery object This means we canrename the object within the context of our ready() handler without af fect ing other code

    jQuery(document)ready(function($) Code using $ as usual goes here)

    Example 1 Display a message when the DOM is loaded

    Javascript

    $(document)ready(function () $(p)text(The DOM is now loaded and can be manipulated))

    CSS

    p colorred

    HTML

    ltpgtNot loaded yetltpgt

    die

    Remove all event handlers previously at tached using live() f rom the elements

    Added in version 141

    die()jQuery

    Any handler that has been at tached with live() can be removed with die() This method isanalogous to calling unbind() with no arguments which is used to remove all handlers at tached

    with bind() See the discussions of live() and unbind() for further details

    Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

    die

    Remove an event handler previously at tached using live() f rom the elements

    Added in version 143

    die(eventTypes)jQuery

    eventTypesMap A map of one or more event types such as click or keydown and theircorresponding funct ions that are no longer to be executed

    Any handler that has been at tached with live() can be removed with die() This method isanalogous to unbind() which is used to remove handlers at tached with bind() See thediscussions of live() and unbind() for further details

    Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

    Example 1 Can bind and unbind events to the colored button

    Javascript

    function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(theone)l ive(click aClick) text(Can Click))$(unbind)cl ick(function () $(theone)die(click aClick) text(Does nothing))

    CSS

    button margin5px buttontheone colorred backgroundyellow

    HTML

    ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

    ltdiv style=displaynonegtClickltdivgt

    Example 2 To unbind all live events f rom all paragraphs write

    Javascript

    $(p)die()

    Example 3 To unbind all live click events f rom all paragraphs write

    Javascript

    $(p)die( cl ick )

    Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

    Javascript

    var foo = function () code to handle some kind of event

    $(p)l ive(click foo) now foo wil l be called when paragraphs are cl icked

    $(p)die(click foo) foo wil l no longer be called

    live

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

    Added in version 143

    live(events)jQuery

    eventsObject A map of one or more JavaScript event types and funct ions to executefor them

    This method is a variat ion on the basic bind() method for at taching event handlers to elementsWhen bind() is called the elements that the jQuery object refers to get the handler at tachedelements that get introduced later do not so they would require another bind() call Forinstance consider the HTML

    ltbodygt ltdiv class=clickmegt Click here ltdivgtltbodygt

    To bind a simple click handler to this element

    $(cl ickme)bind(cl ick function() Bound handler called)

    When the element is clicked the handler is called However suppose that af ter this anotherelement is added

    $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

    This new element also matches the selector clickme but since it was added af ter the call tobind() clicks on it will do nothing

    The live() method provides an alternat ive to this behavior To bind a click handler to the targetelement using this method

    $(cl ickme)l ive(cl ick function() Live handler called)

    And then later add a new element

    $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

    Then clicks on the new element will also t rigger the handler

    To unbind the click handlers f rom all ltdiv class=clickmegt that were bound using live() use thedie() method

    $(cl ickme)die(click)

    Event Delegation

    The live() method is able to af fect elements that have not yet been added to the DOM throughthe use of event delegat ion a handler bound to an ancestor element is responsible for eventsthat are t riggered on its descendants The handler passed to live() is never bound to anelement instead live() binds a special handler to the root of the DOM tree In the exampleabove when the new element is clicked the following steps occur

    1 A click event is generated and passed to the ltdivgt for handling

    2 No handler is direct ly bound to the ltdivgt so the event bubbles up the DOM tree

    3 The event bubbles up unt il it reaches the root of the t ree which is where live() binds itsspecial handlers by default

    As of jQuery 14 event bubbling can optionally stop at a DOM element context

    4 The special click handler bound by live() executes

    5 This handler tests the target of the event object to see whether it should cont inue Thistest is performed by checking if $(eventtarget)closest(clickme) is able to locate amatching element

    6 If a matching element is found the original handler is called on it

    Because the test in step 5 is not performed unt il the event occurs elements can be added atany t ime and st ill respond to events

    See the discussion for bind() for more informat ion on event binding

    Multiple Events

    As of jQuery 141 live() can accept mult iple space-separated events similar to thefunct ionality provided in bind() For example you can live bind the mouseover and mouseoutevents at the same t ime like so

    $(hoverme)l ive(mouseover mouseout function(event) if ( eventtype == mouseover ) do something on mouseover else do something on mouseout )

    As of jQuery 143 you can bind mult iple live event handlers simultaneously by passing a map ofevent typehandler pairs

    $(a)l ive( cl ick function() do something on click mouseover function() do something on mouseover )

    Event Data

    As of jQuery 14 the opt ional eventData parameter is available for passing addit ionalinformat ion to the handler One handy use of this parameter is to work around issues causedby closures See the bind() methods Passing Event Data discussion for more informat ion

    Event Context

    As of jQuery 14 live events can be bound to a DOM element context rather than to thedefault document root To set this context use the jQuery() funct ions second argumentpassing in a single DOM element (as opposed to a jQuery collect ion or a selector)

    $(divcl ickme $(container)[0])l ive(click function() Live handler called)

    The live handler in this example is called only when ltdiv class=clickmegt is a descendant of anelement with an ID of container

    Caveats

    The live() technique is useful but due to its special approach cannot be simply subst ituted forbind() in all cases Specif ic dif ferences include

    DOM traversal methods are not supported for f inding elements to send to live()Rather the live() method should always be called direct ly af ter a selector as in theexample above

    To stop further handlers f rom execut ing af ter one bound using live() the handler mustreturn false Calling stopPropagat ion() will not accomplish this

    The paste and reset events in addit ion to change when used with inputs of type f ileare not fully supported by the live() method due to issues with simulat ing event bubblingin Internet Explorer In these cases the bind() method can be used instead

    In jQuery 13x only the following JavaScript events (in addit ion to custom events)could be bound with live() click dblclick keydown keypress keyup mousedown

    mousemove mouseout mouseover and mouseup

    As of jQuery 14 the live() method supports custom events as well as allJavaScript events that bubble

    As of jQuery 141 even focus and blur work with live (mapping to themore appropriate bubbling events focusin and focusout)

    As of jQuery 141 the hover event can be specified (mapping tomouseenter and mouseleave which in turn are mapped to mouseover andmouseout)

    Example 1 Click a paragraph to add another Note that live() binds the click event to allparagraphs - even new ones

    Javascript

    $(p)l ive(click function() $(this)after(ltpgtAnother paragraphltpgt))

    CSS

    p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

    HTML

    ltpgtClick meltpgt

    ltspangtltspangt

    Example 2 Cancel a default act ion and prevent it f rom bubbling up by returning false

    Javascript

    $(a)l ive(click function() return false )

    Example 3 Cancel only the default act ion by using the preventDefault method

    Javascript

    $(a)l ive(click function(event) eventpreventDefault())

    Example 4 Bind custom events with live()

    Javascript

    $(p)l ive(myCustomEvent function(e myName myValue) $(this)text(Hi there) $(span)stop()css(opacity 1) text(myName = + myName) fadeIn(30)fadeOut(1000))$(button)cl ick(function () $(p)trigger(myCustomEvent))

    CSS

    p colorred span colorblue

    HTML

    ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

    Example 5 Use a map to bind mult iple live event handlers Note that live() binds the clickmouseover and mouseout events to all paragraphs acirceurordquo even new ones

    Javascript

    $(p)l ive( cl ick function() $(this)after(ltpgtAnother paragraphltpgt) mouseover function() $(this)addClass(over) mouseout function() $(this)removeClass(over) )

    CSS

    p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

    HTML

    ltpgtClick meltpgt ltspangtltspangt

    triggerHandler

    Execute all handlers at tached to an element for an event

    Added in version 12

    triggerHandler(eventType extraParameters)Object

    eventTypeString A string containing a JavaScript event type such as click orsubmit

    extraParametersArray An array of addit ional parameters to pass along to the eventhandler

    The t riggerHandler() method behaves similarly to t rigger() with the following except ions

    The t riggerHandler() method does not cause the default behavior of an event to occur(such as a form submission)

    While t rigger() will operate on all elements matched by the jQuery object t riggerHandler() only af fects the f irst matched element

    Events created with t riggerHandler() do not bubble up the DOM hierarchy if they arenot handled by the target element direct ly they do nothing

    Instead of returning the jQuery object (to allow chaining) t riggerHandler() returnswhatever value was returned by the last handler it caused to be executed If no handlersare t riggered it returns undef ined

    For more informat ion on this method see the discussion for t rigger()

    Example 1 If you called t riggerHandler() on a focus event - the browsers default focus act ionwould not be triggered only the event handlers bound to the focus event

    Javascript

    $(old)cl ick(function()$(input)trigger(focus))$(new)cl ick(function()$(input)triggerHandler(focus))$(input)focus(function()$(ltspangtFocusedltspangt)appendTo(body)fadeOut(1000))

    HTML

    ltbutton id=oldgttrigger(focus)ltbuttongtltbutton id=newgttriggerHandler(focus)ltbuttongtltbrgtltbrgt

    ltinput type=text value=To Be Focusedgt

    trigger

    Execute all handlers and behaviors at tached to the matched elements for the given event type

    Added in version 13

    trigger(event)jQuery

    eventEvent A jQueryEvent object

    Any event handlers at tached with bind() or one of its shortcut methods are t riggered when thecorresponding event occurs They can be f ired manually however with the t rigger() method Acall to t rigger() executes the handlers in the same order they would be if the event weretriggered naturally by the user

    $(foo)bind(cl ick function() alert($(this)text()) ) $(foo)trigger(cl ick)

    As of jQuery 13 t rigger()ed events bubble up the DOM tree an event handler can stop thebubbling by returning false f rom the handler or calling the stopPropagat ion() method on theevent object passed into the event Although t rigger() simulates an event act ivat ion completewith a synthesized event object it does not perfect ly replicate a naturally-occurring event

    To trigger handlers bound via jQuery without also t riggering the nat ive event use

    t riggerHandler() instead

    When we def ine a custom event type using the bind() method the second argument tot rigger() can become useful For example suppose we have bound a handler for the customevent to our element instead of the built -in click 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 f irst parameter to an event handler but if addit ionalparameters are specif ied during a t rigger() call these parameters will be passed along to thehandler as well To pass more than one parameter use an array as shown here As of jQuery162 a single parameter can be passed without using an array

    Note the dif ference between the extra parameters were passing here and the eventDataparameter to the bind() method Both are mechanisms for passing informat ion to an eventhandler but the extraParameters argument to t rigger() allows informat ion to be determined atthe t ime the event is t riggered while the eventData argument to bind() requires the informat ionto be already computed at the t ime the handler is bound

    Example 1 Clicks to button 2 also t rigger a click for button 1

    Javascript

    $(buttonfirst)cl ick(function () update($(spanfirst)))$(buttonlast)cl ick(function () $(buttonfirst)trigger(cl ick)

    update($(spanlast)))

    function update(j) var n = parseInt(jtext() 10)j text(n + 1)

    CSS

    button margin10px div colorblue font-weightbold span colorred

    HTML

    ltbuttongtButton 1ltbuttongtltbuttongtButton 2ltbuttongtltdivgtltspangt0ltspangt button 1 clicksltdivgt

    ltdivgtltspangt0ltspangt button 2 clicksltdivgt

    Example 2 To submit the f irst form without using the submit() funct ion t ry

    Javascript

    $(formfirst)trigger(submit)

    Example 3 To submit the f irst form without using the submit() funct ion t ry

    Javascript

    var event = jQueryEvent(submit)$(formfirst)trigger(event)if ( eventisDefaultPrevented() ) Perform an action

    Example 4 To pass arbit rary data to an event

    Javascript

    $(p)cl ick( function (event a b) when a normal cl ick fires a and b are undefined for a trigger l ike below a refers to foo and b refers to bar

    )trigger(click [foo bar])

    Example 5 To pass arbit rary data through an event object

    Javascript

    var event = jQueryEvent(logged)eventuser = fooeventpass = bar$(body)trigger(event)

    Example 6 Alternat ive way to pass data through an event object

    Javascript

    $(body)trigger(typeloggeduserfoopassbar

    )

    one

    Attach a handler to an event for the elements The handler is executed at most once perelement

    Added in version 11

    one(eventType eventData handler(eventObject))jQuery

    eventTypeString A string containing one or more JavaScript event typessuch as click or submit or custom event names

    eventDataObject (opt ional) A map of data that will be passed to theevent handler

    handler(eventObject)Funct ion A funct ion to execute at the t ime the event is t riggered

    This method is ident ical to bind() except that the handler is unbound af ter its f irst invocat ionFor example

    $(foo)one(click function() alert(This wil l be displayed only once))

    After the code is executed a click on the element with ID foo will display the alert Subsequentclicks will do nothing This code is equivalent to

    $(foo)bind(click function( event ) alert(This wil l be displayed only once) $(this)unbind( event ))

    In other words explicit ly calling unbind() f rom within a regularly-bound handler has exact ly thesame effect

    If the f irst argument contains more than one space-separated event types the event handler is

    called once for each event type

    Example 1 Tie a one-t ime click to each div

    Javascript

    var n = 0$(div)one(click function() var index = $(div)index(this) $(this)css( borderStyleinset cursorauto ) $(p)text(Div at index + index + cl icked + Thats + ++n + total cl icks))

    CSS

    div width60px height60px margin5px floatleftbackgroundgreen border10px outset cursorpointer p colorred margin0 clearleft

    HTML

    ltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

    ltpgtClick a green squareltpgt

    Example 2 To display the text of all paragraphs in an alert box the f irst t ime each of them isclicked

    Javascript

    $(p)one(click function()alert( $(this)text() ))

    unbind

    Remove a previously-at tached event handler f rom the elements

    Added in version 10

    unbind(event)jQuery

    eventObject A JavaScript event object as passed to an event handler

    Any handler that has been at tached with bind() can be removed with unbind() In the simplestcase with no arguments unbind() removes all handlers at tached to the elements

    $(foo)unbind()

    This version removes the handlers regardless of type To be more precise we can pass anevent type

    $(foo)unbind(cl ick)

    By specifying the click event type only handlers for that event type will be unbound Thisapproach can st ill have negat ive ramif icat ions if other scripts might be at taching behaviors tothe same element however Robust and extensible applicat ions typically demand the two-argument version for this reason

    var handler = function() alert(The quick brown fox jumps over the lazy dog)$(foo)bind(cl ick handler)$(foo)unbind(cl ick handler)

    By naming the handler we can be assured that no other funct ions are caught in the crossf ireNote that the following will not work

    $(foo)bind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

    wil l NOT work$(foo)unbind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

    Even though the two funct ions are ident ical in content they are created separately and soJavaScript is f ree to keep them as dist inct funct ion objects To unbind a part icular handler weneed a reference to that funct ion and not a dif ferent one that happens to do the same thing

    Note Because the live() method binds event handlers to document by defaultcalling unbind() on document will unbind the handlers bound by live() as wellFor example $(document)unbind(click) will remove not only$(document)bind(click fn1)

    but also

    $(afoo)live(click fn2)

    Note Using a proxied function to unbind an event on an element will unbind allproxied functions on that element as the same proxy function is used for allproxied events To allow unbinding a specific event use unique class names onthe event (eg clickproxy1 clickproxy2) when attaching them

    Using Namespaces

    Instead of maintaining references to handlers in order to unbind them we can namespace theevents and use this capability to narrow the scope of our unbinding act ions As shown in thediscussion for the bind() method namespaces are def ined by using a period () character whenbinding a handler

    $(foo)bind(cl ickmyEvents handler)

    When a handler is bound in this fashion we can st ill unbind it the normal way

    $(foo)unbind(cl ick)

    However if we want to avoid af fect ing other handlers we can be more specif ic

    $(foo)unbind(cl ickmyEvents)

    We can also unbind all of the handlers in a namespace regardless of event type

    $(foo)unbind(myEvents)

    It is part icularly useful to at tach namespaces to event bindings when we are developing plug-insor otherwise writ ing code that may interact with other event-handling code in the future

    Using the Event Object

    The third form of the unbind() method is used when we wish to unbind a handler f rom withinitself For example suppose we wish to t rigger an event handler only three t imes

    var timesClicked = 0$(foo)bind(cl ick function(event) alert(The quick brown fox jumps over the lazy dog) timesClicked++ if (timesClicked gt= 3) $(this)unbind(event) )

    The handler in this case must take a parameter so that we can capture the event object anduse it to unbind the handler af ter the third click The event object contains the contextnecessary for unbind() to know which handler to remove This example is also an illustrat ion ofa closure Since the handler refers to the t imesClicked variable which is def ined outside thefunct ion increment ing the variable has an ef fect even between invocat ions of the handler

    Example 1 Can bind and unbind events to the colored button

    Javascript

    function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () could use bind(cl ick aClick) instead but for variety$(theone)cl ick(aClick) text(Can Click))$(unbind)cl ick(function () $(theone)unbind(cl ick aClick) text(Does nothing))

    CSS

    button margin5px buttontheone colorred backgroundyellow

    HTML

    ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

    ltdiv style=displaynonegtClickltdivgt

    Example 2 To unbind all events f rom all paragraphs write

    Javascript

    $(p)unbind()

    Example 3 To unbind all click events f rom all paragraphs write

    Javascript

    $(p)unbind( cl ick )

    Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

    Javascript

    var foo = function () code to handle some kind of event

    $(p)bind(click foo) now foo wil l be called when paragraphs are cl icked

    $(p)unbind(click foo) foo wil l no longer be called

    bind

    Attach a handler to an event for the elements

    Added in version 14

    bind(events)jQuery

    eventsObject A map of one or more JavaScript event types and funct ions to executefor them

    The bind() method is the primary means of at taching behavior to a document All JavaScriptevent types such as focus mouseover and resize are allowed for eventType The error eventon the window object uses nonstandard convent ions and is not supported by jQuery at tach ahandler direct ly to the window object instead The beforeunload event is supported cross-browser in jQuery 151 and 16+ but is not supported in IE for jQuery 152 due to a regression

    The jQuery library provides shortcut methods for binding the standard event types such asclick() for bind(click) A descript ion of each can be found in the discussion of its shortcutmethod blur focus focusin focusout load resize scroll unload click dblclick mousedownmouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error

    Any string is legal for eventType if the string is not the name of a nat ive JavaScript event thenthe handler is bound to a custom event These events are never called by the browser but maybe triggered manually f rom other JavaScript code using t rigger() or t riggerHandler()

    If the eventType string contains a period () character then the event is namespaced Theperiod character separates the event f rom its namespace For example in the callbind(clickname handler) the string click is the event type and the string name is thenamespace Namespacing allows us to unbind or t rigger some events of a type withoutaf fect ing others See the discussion of unbind() for more informat ion

    When an event reaches an element all handlers bound to that event type for the element aref ired If there are mult iple handlers registered they will always execute in the order in which theywere bound After all handlers have executed the event cont inues along the normal eventpropagat ion path

    A basic usage of bind() is

    $(foo)bind(cl ick function() alert(User cl icked on foo))

    This code will cause the element with an ID of foo to respond to the click event When a userclicks inside this element thereafter the alert will be shown

    Multiple Events

    Mult iple event types can be bound at once by including each one separated by a space

    $(foo)bind(mouseenter mouseleave function() $(this)toggleClass(entered))

    The ef fect of this on ltdiv id=foogt (when it does not init ially have the entered class) is toadd the entered class when the mouse enters the ltdivgt and remove the class when themouse leaves

    As of jQuery 14 we can bind mult iple event handlers simultaneously by passing a map of eventtypehandler pairs

    $(foo)bind( cl ick function() do something on click mouseenter function() do something on mouseenter )

    Event Handlers

    The handler parameter takes a callback funct ion as shown above Within the handler thekeyword this refers to the DOM element to which the handler is bound To make use of theelement in jQuery it can be passed to the normal $() funct ion For example

    $(foo)bind(cl ick function() alert($(this)text()))

    After this code is executed when the user clicks inside the element with an ID of foo its textcontents will be shown as an alert

    As of jQuery 142 duplicate event handlers can be bound to an element instead of beingdiscarded For example

    function test() alert(Hello) $(button)cl ick( test )$(button)cl ick( test )

    The above will generate two alerts when the button is clicked

    In jQuery 143 you can now pass in false in place of an event handler This will bind an eventhandler that s equivalent to funct ion() return false This funct ion can be removed at a latert ime by calling unbind( eventName false )

    The Event object

    The handler callback funct ion can also take parameters When the funct ion is called theJavaScript event object will be passed to the f irst parameter

    The event object is of ten unnecessary and the parameter omit ted as suff icient context isusually available when the handler is bound to know exact ly what needs to be done when thehandler is t riggered However at t imes it becomes necessary to gather more informat ion aboutthe users environment at the t ime the event was init iated View the full Event Object

    Returning false f rom a handler is equivalent to calling both preventDefault () andstopPropagat ion() on the event object

    Using the event object in a handler looks like this

    $(document)ready(function() $(foo)bind(cl ick function(event) alert(The mouse cursor is at ( + eventpageX + + eventpageY + )) ))

    Note the parameter added to the anonymous funct ion This code will cause a click on theelement with ID foo to report the page coordinates of the mouse cursor at the t ime of the click

    Passing Event Data

    The opt ional eventData parameter is not commonly used When provided this argument allowsus to pass addit ional informat ion to the handler One handy use of this parameter is to workaround issues caused by closures For example suppose we have two event handlers that bothrefer to the same external variable

    var message = Spoon$(foo)bind(cl ick function() alert(message))message = Not in the face$(bar)bind(cl ick function() alert(message))

    Because the handlers are closures that both have message in their environment both willdisplay the message Not in the face when triggered The variables value has changed Tosidestep this we can pass the message in using eventData

    var message = Spoon$(foo)bind(cl ick msg message function(event) alert(eventdatamsg))message = Not in the face$(bar)bind(cl ick msg message function(event) alert(eventdatamsg))

    This t ime the variable is not referred to direct ly within the handlers instead the variable is

    passed in by value through eventData which f ixes the value at the t ime the event is boundThe f irst handler will now display Spoon while the second will alert Not in the face

    Note that objects are passed to functions by reference which further complicatesthis scenario

    If eventData is present it is the second argument to the bind() method if no addit ional dataneeds to be sent to the handler then the callback is passed as the second and f inal argument

    See the trigger() method reference for a way to pass data to a handler at the timethe event happens rather than when the handler is bound

    As of jQuery 14 we can no longer at tach data (and thus events) to object embed or appletelements because crit ical errors occur when at taching data to Java applets

    Note Although demonstrated in the next example it is inadvisable to bind handlers to both theclick and dblclick events for the same element The sequence of events t riggered varies f rombrowser to browser with some receiving two click events before the dblclick and others onlyone Double-click sensit ivity (maximum t ime between clicks that is detected as a double click)can vary by operat ing system and browser and is of ten user-conf igurable

    Example 1 Handle click and double-click for the paragraph Note the coordinates are windowrelat ive so in this case relat ive to the demo if rame

    Javascript

    $(p)bind(click function(event)var str = ( + eventpageX + + eventpageY + )$(span)text(Click happened + str))$(p)bind(dblcl ick function()$(span)text(Double-click happened in + thisnodeName))$(p)bind(mouseenter mouseleave function(event)$(this)toggleClass(over))

    CSS

    p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

    HTML

    ltpgtClick or double cl ick hereltpgtltspangtltspangt

    Example 2 To display each paragraphs text in an alert box whenever it is clicked

    Javascript

    $(p)bind(click function()alert( $(this)text() ))

    Example 3 You can pass some extra data before the event handler

    Javascript

    function handler(event) alert(eventdatafoo)$(p)bind(click foo bar handler)

    Example 4 Cancel a default act ion and prevent it f rom bubbling up by returning false

    Javascript

    $(form)bind(submit function() return false )

    Example 5 Cancel only the default act ion by using the preventDefault () method

    Javascript

    $(form)bind(submit function(event) eventpreventDefault())

    Example 6 Stop an event f rom bubbling without prevent ing the default act ion by using thestopPropagat ion() method

    Javascript

    $(form)bind(submit function(event) eventstopPropagation())

    Example 7 Bind custom events

    Javascript

    $(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)cl ick(function () $(p)trigger(myCustomEvent [ John ]))

    CSS

    p colorred span colorblue

    HTML

    ltpgtHas an attached custom eventltpgtltbuttongtTrigger custom eventltbuttongtltspan style=displaynonegtltspangt

    Example 8 Bind mult iple events simultaneously

    Javascript

    $(divtest)bind( cl ick function() $(this)addClass(active) mouseenter function() $(this)addClass(inside) mouseleave function() $(this)removeClass(inside) )

    Deferred Object

    deferredpipe

    Utility method to f ilter andor chain Deferreds

    Added in version 16

    deferredpipe(doneFilter failFilter)Promise

    doneFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isresolved

    failFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isrejected

    The deferredpipe() method returns a new promise that f ilters the status and values of adeferred through a funct ion The doneFilter and failFilter funct ions f ilter the original deferredsresolved rejected status and values These f ilter funct ions can return a new value to bepassed along to the piped promises done() or fail() callbacks or they can return anotherobservable object (Deferred Promise etc) which will pass its resolved rejected status andvalues to the piped promises callbacks If the f ilter funct ion used is null or not specif ied thepiped promise will be resolved or rejected with the same values as the original

    Example 1 Filter resolve value

    Javascript

    var defer = $Deferred() fi ltered = deferpipe(function( value ) return value 2 )

    deferresolve( 5 )fi ltereddone(function( value ) alert( Value is ( 25 = ) 10 + value ))

    Example 2 Filter reject value

    Javascript

    var defer = $Deferred() fi ltered = deferpipe( null function( value ) return value 3 )

    deferreject( 6 )fi lteredfail(function( value ) alert( Value is ( 36 = ) 18 + value ))

    Example 3 Chain tasks

    Javascript

    var request = $ajax( url dataType json ) chained = requestpipe(function( data ) return $ajax( url2 data user datauserId ) )

    chaineddone(function( data ) data retrieved from url2 as provided by the first request)

    deferredalways

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

    Added in version 16

    deferredalways(alwaysCallbacks)Deferred

    alwaysCallbacksFunct ion A funct ion or array of funct ions that is called when theDeferred is resolved or rejected

    The argument can be either a single funct ion or an array of funct ions When the Deferred isresolved or rejected the alwaysCallbacks are called Since deferredalways() returns theDeferred object other methods of the Deferred object can be chained to this one includingaddit ional always() methods When the Deferred is resolved or rejected callbacks are executedin the order they were added using the arguments provided to the resolve reject resolveWithor rejectWith method calls For more informat ion see the documentat ion for Deferred object

    Example 1 Since the jQueryget() method returns a jqXHR object which is derived from aDeferred object we can at tach a callback for both success and error using thedeferredalways() method

    Javascript

    $get(testphp)always( function() alert($get completed with success or error callback arguments) )

    promise

    Return a Promise object to observe when all act ions of a certain type bound to the collect ionqueued or not have f inished

    Added in version 16

    promise(type target)Promise

    typeString (opt ional) The type of queue that needs to be observed

    targetObject (opt ional) Object onto which the promise methods have to be at tached

    The promise() method returns a dynamically generated Promise that is resolved once allact ions of a certain type bound to the collect ion queued or not have ended

    By default type is fx which means the returned Promise is resolved when all animat ions ofthe selected elements have completed

    Resolve context and sole argument is the collect ion onto which promise() has been called

    If target is provided promise() will at tach the methods onto it and then return this object ratherthan create a new one This can be useful to at tach the Promise behavior to an object thatalready exists

    Note The returned Promise is linked to a Deferred object stored on the data() foran element Since the remove() method removes the elements data as well asthe element itself it will prevent any of the elements unresolved Promises fromresolving If it is necessary to remove an element from the DOM before its Promiseis resolved use detach() instead and follow with removeData() after resolution

    Example 1 Using promise() on a collect ion with no act ive animat ion returns a resolved Promise

    Javascript

    var div = $( ltdiv gt )

    divpromise()done(function( arg1 ) wil l fire right away and alert true alert( this === div ampamp arg1 === div ))

    Example 2 Resolve the returned Promise when all animat ions have ended (including thoseinit iated in the animat ion callback or added later on)

    CSS

    div height 50px width 50px float left margin-right 10px display none background-color 090

    HTML

    ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

    Javascript

    $(button)bind( cl ick function() $(p)append( Started) $(div)each(function( i ) $( this )fadeIn()fadeOut( 1000 (i+1) ) )

    $( div )promise()done(function() $( p )append( Finished ) ))

    Example 3 Resolve the returned Promise using a $when() statement (the promise() methodmakes it possible to do this with jQuery collect ions)

    CSS

    div height 50px width 50px float left margin-right 10px display none background-color 090

    HTML

    ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

    Javascript

    var effect = function() return $(div)fadeIn(800)delay(1200)fadeOut()

    $(button)bind( cl ick function() $(p)append( Started )

    $when( effect() )done(function() $(p)append( Finished ) ))

    deferredpromise

    Return a Deferreds Promise object

    Added in version 15

    deferredpromise(target)Promise

    targetObject (opt ional) Object onto which the promise methods have to be at tached

    The deferredpromise() method allows an asynchronous funct ion to prevent other code frominterfering with the progress or status of its internal request The Promise exposes only theDeferred methods needed to at tach addit ional handlers or determine the state (then done failisResolved and isRejected) but not ones that change the state (resolve reject resolveWithand rejectWith) As of jQuery 16 the Promise also exposes the always and pipe Deferredmethods

    If target is provided deferredpromise() will at tach the methods onto it and then return thisobject rather than create a new one This can be useful to at tach the Promise behavior to anobject that already exists

    If you are creat ing a Deferred keep a reference to the Deferred so that it can be resolved orrejected at some point Return only the Promise object via deferredpromise() so other codecan register callbacks or inspect the current state

    For more informat ion see the documentat ion for Deferred object

    Example 1 Create a Deferred and set two t imer-based funct ions to either resolve or reject theDeferred af ter a random interval Whichever one f ires f irst wins and will call one of thecallbacks The second t imeout has no ef fect since the Deferred is already complete (in aresolved or rejected state) f rom the f irst t imeout act ion

    Javascript

    Create a Deferred and return its Promisefunction asyncEvent() var dfd = new jQueryDeferred() setTimeout(function() dfdresolve(hurray) Mathfloor(Mathrandom()1500)) setTimeout(function() dfdreject(sorry) Mathfloor(Mathrandom()1500)) return dfdpromise()

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

    Example 2 Use the target argument to promote an exist ing object to a Promise

    Javascript

    Existing objectvar obj = hello function( name ) alert( Hello + name ) Create a Deferreddefer = $Deferred()

    Set object as a promisedeferpromise( obj )

    Resolve the deferreddeferresolve( John )

    Use the object as a Promiseobjdone(function( name ) objhello( name ) wil l alert Hello John)hello( Karl ) wil l alert Hello Karl

    jQuerywhen see Core

    deferredresolveWith

    Resolve a Deferred object and call any doneCallbacks with the given context and args

    Added in version 15

    deferredresolveWith(context args)Deferred

    context Object Context passed to the doneCallbacks as the this object

    argsArray (opt ional) An opt ional array of arguments that are passed to thedoneCallbacks

    Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

    When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

    deferredrejectWith

    Reject a Deferred object and call any failCallbacks with the given context and args

    Added in version 15

    deferredrejectWith(context args)Deferred

    context Object Context passed to the failCallbacks as the this object

    argsArray (opt ional) An opt ional array of arguments that are passed to thefailCallbacks

    Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

    When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

    deferredfail

    Add handlers to be called when the Deferred object is rejected

    Added in version 15

    deferredfail(failCallbacks failCallbacks)Deferred

    failCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is rejected

    failCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is rejected

    The deferredfail() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is rejected the failCallbacks are calledCallbacks are executed in the order they were added Since deferredfail() returns the deferredobject other methods of the deferred object can be chained to this one including addit ionaldeferredfail() methods The failCallbacks are executed using the arguments provided to thedeferredreject() or deferredrejectWith() method call in the order they were added For moreinformat ion see the documentat ion for Deferred object

    Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred you can at tach a success and failure callback using the deferreddone() anddeferredfail() methods

    Javascript

    $get(testphp) done(function() alert($get succeeded) ) fai l(function() alert($get fai led) )

    deferreddone

    Add handlers to be called when the Deferred object is resolved

    Added in version 15

    deferreddone(doneCallbacks doneCallbacks)Deferred

    doneCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is resolved

    doneCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is resolved

    The deferreddone() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is resolved the doneCallbacks are calledCallbacks are executed in the order they were added Since deferreddone() returns thedeferred object other methods of the deferred object can be chained to this one includingaddit ional done() methods When the Deferred is resolved doneCallbacks are executed usingthe arguments provided to the resolve or resolveWith method call in the order they were addedFor more informat ion see the documentat ion for Deferred object

    Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach a success callback using the done() method

    Javascript

    $get(testphp)done(function() alert($get succeeded) )

    Example 2 Resolve a Deferred object when the user clicks a button t riggering a number ofcallback funct ions

    Javascript

    3 functions to call when the Deferred object is resolvedfunction fn1() $(p)append( 1 )function fn2() $(p)append( 2 )function fn3(n) $(p)append(n + 3 + n)

    create a deferred objectvar dfd = $Deferred()

    add handlers to be called when dfd is resolveddfd done() can take any number of functions or arrays of functionsdone( [fn1 fn2] fn3 [fn2 fn1] ) we can chain done methods toodone(function(n) $(p)append(n + were done))

    resolve the Deferred object when the button is cl icked$(button)bind(click function() dfdresolve(and))

    HTML

    ltbuttongtGoltbuttongt ltpgtReadyltpgt

    deferredthen

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

    Added in version 15

    deferredthen(doneCallbacks failCallbacks)Deferred

    doneCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isresolved

    failCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isrejected

    Both arguments can be either a single funct ion or an array of funct ions Either argument can

    also be null if no callback of that type is desired Alternat ively use done() or fail() to set onlydoneCallbacks or failCallbacks When the Deferred is resolved the doneCallbacks are called Ifthe Deferred is instead rejected the failCallbacks are called Callbacks are executed in the orderthey were added Since deferredthen returns the deferred object other methods of thedeferred object can be chained to this one including addit ional then() methods For moreinformat ion see the documentat ion for Deferred object

    Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach handlers using the then method

    Javascript

    $get(testphp)then( function() alert($get succeeded) function() alert($get fai led) )

    deferredreject

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

    Added in version 15

    deferredreject(args)Deferred

    argsObject Opt ional arguments that are passed to the failCallbacks

    Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

    When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

    deferredisRejected

    Determine whether a Deferred object has been rejected

    Added in version 15

    deferredisRejected()Boolean

    Returns t rue if the Deferred object is in the rejected state meaning that either deferredreject()

    or deferredrejectWith() has been called for the object and the failCallbacks have been called (orare in the process of being called)

    Note that a Deferred object can be in one of three states unresolved resolved or rejecteduse deferredisResolved() to determine whether the Deferred object is in the resolved stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

    deferredisResolved

    Determine whether a Deferred object has been resolved

    Added in version 15

    deferredisResolved()Boolean

    Returns t rue if the Deferred object is in the resolved state meaning that eitherdeferredresolve() or deferredresolveWith() has been called for the object and thedoneCallbacks 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 rejecteduse deferredisRejected() to determine whether the Deferred object is in the rejected stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

    deferredresolve

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

    Added in version 15

    deferredresolve(args)Deferred

    argsObject Opt ional arguments that are passed to the doneCallbacks

    When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

    Effects

    fadeToggle

    Display or hide the matched elements by animat ing their opacity

    Added in version 144

    fadeToggle(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackFunct ion (opt ional) A funct ion to call once the animat ion is complete

    The fadeToggle() method animates the opacity of the matched elements When called on avisible element the element s display style property is set to none once the opacity reaches 0so the element no longer af fects the layout of the page

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    Easing

    The string represent ing an easing funct ion specif ies the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easing implementat ions in thejQuery library are the default called swing and one that progresses at a constant pace calledlinear More easing funct ions are available with the use of plug-ins most notably the jQuery UIsuite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

    As of jQuery 16 the promise() method can be used in conjunct ion with the deferreddone()method to execute a single callback for the animat ion as a whole when all matching elementshave completed their animat ions ( See the example for promise() )

    Example 1 Fades f irst paragraph in or out complet ing the animat ion within 600 millisecondsand using a linear easing Fades last paragraph in or out for 200 milliseconds insert ing af inished message upon complet ion

    Javascript

    $(buttonfirst)cl ick(function() $(pfirst)fadeToggle(slow l inear))$(buttonlast)cl ick(function () $(plast)fadeToggle(fast function () $(log)append(ltdivgtfinishedltdivgt) ))

    HTML

    ltbuttongtfadeToggle p1ltbuttongtltbuttongtfadeToggle p2ltbuttongtltpgtThis paragraph has a slow l inear fadeltpgt

    ltpgtThis paragraph has a fast animationltpgtltdiv id=loggtltdivgt

    jQueryfxinterval

    The rate (in milliseconds) at which animat ions f ire

    Added in version 143

    This property can be manipulated to adjust the number of f rames per second at whichanimat ions will run The default is 13 milliseconds Making this a lower number could make theanimat ions run smoother in faster browsers (such as Chrome) but there may be performanceand CPU implicat ions of doing so

    Since jQuery uses one global interval no animat ion should be running or all animat ions shouldstop for the change of this property to take ef fect

    NotejQueryfxinterval current ly has no ef fect in browsers that support therequestAnimat ionFrame property such as Google Chrome 11 This behavior is subject tochange in a future release

    Example 1 Cause all animat ions to run with less f rames

    Javascript

    jQueryfxinterval = 100

    $(input)cl ick(function() $(div)toggle( 3000 ))

    CSS

    div width50px height30px margin5px floatleft backgroundgreen

    HTML

    ltpgtltinput type=button value=Rungtltpgtltdivgtltdivgt

    delay

    Set a t imer to delay execut ion of subsequent items in the queue

    Added in version 14

    delay(durat ion queueName)jQuery

    durat ionInteger An integer indicat ing the number of milliseconds to delay execut ionof the next item in the queue

    queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

    Added to jQuery in version 14 the delay() method allows us to delay the execut ion offunct ions that follow it in the queue It can be used with the standard ef fects queue or with acustom queue Only subsequent events in a queue are delayed for example this will not delaythe no-arguments forms of show() or hide() which do not use the ef fects queue

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    Using the standard ef fects queue we can for example set an 800-millisecond delay betweenthe slideUp() and fadeIn() of ltdiv id=foogt

    $(foo)sl ideUp(300)delay(800)fadeIn(400)

    When this statement is executed the element slides up for 300 milliseconds and then pausesfor 800 milliseconds before fading in for 400 milliseconds

    The delay() method is best for delaying between queued jQuery effects Because

    it is limitedacirceurordquoit doesnt for example offer a way to cancel the delayacirceurordquodelay() isnot a replacement for JavaScripts native setTimeout function which may be moreappropriate for certain use cases

    Example 1 Animate the hiding and showing of two divs delaying the f irst before showing it

    CSS

    div position absolute width 60px height 60px float left first background-color 3f3 left 0second background-color 33f left 80px

    Javascript

    $(button)cl ick(function() $(divfirst)sl ideUp(300)delay(800)fadeIn(400) $(divsecond)sl ideUp(300)fadeIn(400) )

    HTML

    ltpgtltbuttongtRunltbuttongtltpgtltdiv class=firstgtltdivgtltdiv class=secondgtltdivgt

    jQueryfxoff

    Globally disable all animat ions

    Added in version 13

    When this property is set to t rue all animat ion methods will immediately set elements to theirf inal state when called rather than displaying an ef fect This may be desirable for a couplereasons

    jQuery is being used on a low-resource device

    Users are encountering accessibility problems with the animat ions (see the art icle TurnOff Animat ion for more informat ion)

    Animat ions can be turned back on by sett ing the property to false

    Example 1 Toggle animat ion on and of f

    Javascript

    var toggleFx = function() $fxoff = $fxofftoggleFx()

    $(button)cl ick(toggleFx)

    $(input)cl ick(function() $(div)toggle(slow))

    CSS

    div width50px height30px margin5px floatleft backgroundgreen

    HTML

    ltpgtltinput type=button value=Rungt ltbuttongtToggle fxltbuttongtltpgtltdivgtltdivgt

    clearQueue see Data

    dequeue see Data

    queue see Data

    queue see Data

    stop

    Stop the current ly-running animat ion on the matched elements

    Added in version 12

    stop(clearQueue jumpToEnd)jQuery

    clearQueueBoolean (opt ional) A Boolean indicat ing whether to remove queuedanimat ion as well Defaults to false

    jumpToEndBoolean (opt ional) A Boolean indicat ing whether to complete the currentanimat ion immediately Defaults to false

    When stop() is called on an element the current ly-running animat ion (if any) is immediatelystopped If for instance an element is being hidden with slideUp() when stop() is called theelement will now st ill be displayed but will be a f ract ion of its previous height Callback funct ions

    are not called

    If more than one animat ion method is called on the same element the later animat ions areplaced in the ef fects queue for the element These animat ions will not begin unt il the f irst onecompletes When stop() is called the next animat ion in the queue begins immediately If theclearQueue parameter is provided with a value of t rue then the rest of the animat ions in thequeue are removed and never run

    If the jumpToEnd property is provided with a value of t rue the current animat ion stops but theelement is immediately given its target values for each CSS property In our above slideUp()example the element would be immediately hidden The callback funct ion is then immediatelycalled if provided

    The usefulness of the stop() method is evident when we need to animate an element onmouseenter and mouseleave

    ltdiv id=hovermegt Hover me ltimg id=hoverme src=bookpng alt= width=100 height=123 gtltdivgt

    We can create a nice fade ef fect without the common problem of mult iple queued animat ionsby adding stop(true t rue) to the chain

    $(hoverme-stop-2)hover(function() $(this)find( img)stop(true true)fadeOut() function() $(this)find( img)stop(true true)fadeIn())

    Animations may be stopped globally by setting the property $fxoff to true Whenthis is done all animation methods will immediately set elements to their finalstate when called rather than displaying an effect

    Example 1 Click the Go button once to start the animat ion then click the STOP button to stopit where it s current ly posit ioned Another opt ion is to click several buttons to queue them upand see that stop just kills the current ly playing one

    Javascript

    Start animation $(go)cl ick(function()$(block)animate(left +=100px 2000))

    Stop animation when button is cl icked $(stop)cl ick(function()$(block)stop())

    Start animation in the opposite direction $(back)cl ick(function()$(block)animate(left -=100px 2000))

    HTML

    ltbutton id=gogtGoltbuttongt ltbutton id=stopgtSTOPltbuttongtltbutton id=backgtBackltbuttongtltdiv class=blockgtltdivgt

    CSS

    div position absolute background-color abcleft 0pxtop30pxwidth 60px height 60pxmargin 5px

    animate

    Perform a custom animat ion of a set of CSS propert ies

    Added in version 10

    animate(propert ies opt ions)jQuery

    propert iesMap A map of CSS propert ies that the animat ion will move toward

    opt ionsMap A map of addit ional opt ions to pass to the method Supported keys

    durat ion A string or number determining how long theanimat ion will run

    easing A string indicat ing which easing funct ion to use for thetransit ion

    complete A funct ion to call once the animat ion is completestep A funct ion to be called af ter each step of the animat ionqueue A Boolean indicat ing whether to place the animat ion in

    the ef fects queue If false the animat ion will begin immediatelyspecialEasing A map of one or more of the CSS propert ies

    def ined by the propert ies argument and their correspondingeasing funct ions (added 14)

    The animate() method allows us to create animat ion ef fects on any numeric CSS property Theonly required parameter is a map of CSS propert ies This map is similar to the one that can besent to the css() method except that the range of propert ies is more restrict ive

    Animation Properties and Values

    All animated propert ies should be animated to a single numeric value except as noted belowmost propert ies that are non-numeric cannot be animated using basic jQuery funct ionality (Forexample width height or lef t can be animated but background-color cannot be) Propertyvalues are t reated as a number of pixels unless otherwise specif ied The units em and can bespecif ied where applicable

    In addit ion to style propert ies some non-style propert ies such as scrollTop and scrollLef t aswell as custom propert ies can be animated

    Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

    In addit ion to numeric values each property can take the strings show hide and toggleThese shortcuts allow for custom hiding and showing animat ions that take into account thedisplay type of the element

    Animated propert ies can also be relat ive If a value is supplied with a leading += or -= sequenceof characters then the target value is computed by adding or subtract ing the given numberfrom the current value of the property

    Unlike shorthand animat ion methods such as slideDown() and fadeIn() the animate() methoddoes not make hidden elements visible as part of the ef fect For example given$(someElement )hide()animate(height20px 500) the animat ion will run but the element willremain hidden

    Duration

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    Complete Function

    If supplied the complete callback funct ion is f ired once the animat ion is complete This can beuseful for stringing dif ferent animat ions together in sequence The callback is not sent anyarguments but this is set to the DOM element being animated If mult iple elements areanimated the callback is executed once per matched element not once for the animat ion as awhole

    Basic Usage

    To animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 style=position relative left 10px gt

    To animate the opacity lef t of fset and height of the image simultaneously

    $(clickme)cl ick(function() $(book)animate( opacity 025 left +=50 height toggle 5000 function() Animation complete ))

    Note that the target value of the height property is toggle Since the image was visible beforethe animat ion shrinks the height to 0 to hide it A second click then reverses this t ransit ion

    The opacity of the image is already at its target value so this property is not animated by thesecond click Since the target value for lef t is a relat ive value the image moves even farther tothe right during this second animat ion

    Direct ional propert ies (top right bot tom lef t ) have no discernible ef fect on elements if theirposit ion style property is stat ic which it is by default

    Note The jQuery UI project extends the animate() method by allowing some non-numeric styles such as colors to be animated The project also includesmechanisms for specifying animations through CSS classes rather than individualattributes

    Note if attempting to animate an element with a height or width of 0px wherecontents of the element are visible due to overflow jQuery may clip this overflowduring animation By fixing the dimensions of the original element being hiddenhowever it is possible to ensure that the animation runs smoothly A clearfix canbe used to automatically fix the dimensions of your main element without the needto set this manually

    Step Function

    The second version of animate() provides a step opt ion acirceurordquo a callback funct ion that is f ired ateach step of the animat ion This funct ion is useful for enabling custom animat ion types oraltering the animat ion as it is occurring It accepts two arguments (now and fx) and this is setto the DOM element being animated

    now the numeric value of the property being animated at each step

    fx a reference to the jQueryfx prototype object which contains a number of propert iessuch as elem for the animated element start and end for the f irst and last value of theanimated property respect ively and prop for the property being animated

    Note that the step funct ion is called for each animated property on each animated element Forexample given two list items the step funct ion f ires four t imes at each step of the animat ion

    $( l i )animate( opacity 5 height 50 step function(now fx) var data = fxelemid + + fxprop + + now $(body)append(ltdivgt + data + ltdivgt) )

    Easing

    The remaining parameter of animate() is a string naming an easing funct ion to use An easingfunct ion specif ies the speed at which the animat ion progresses at dif ferent points within theanimat ion The only easing implementat ions in the jQuery library are the default called swingand one that progresses at a constant pace called linear More easing funct ions are availablewith the use of plug-ins most notably the jQuery UI suite

    Per-property Easing

    As of jQuery version 14 you can set per-property easing funct ions within a single animate()call In the f irst version of animate() each property can take an array as its value The f irstmember of the array is the CSS property and the second member is an easing funct ion If a per-property easing funct ion is not def ined for a part icular property it uses the value of theanimate() methods opt ional easing argument If the easing argument is not def ined thedefault swing funct ion is used

    For example to simultaneously animate the width and height with the swing easing funct ionand the opacity with the linear easing funct ion

    $(clickme)cl ick(function() $(book)animate( width [toggle swing] height [toggle swing] opacity toggle 5000 l inear function() $(this)after(ltdivgtAnimation completeltdivgt) ))

    In the second version of animate() the opt ions map can include the specialEasing propertywhich is itself a map of CSS propert ies and their corresponding easing funct ions For exampleto simultaneously animate the width using the linear easing funct ion and the height using the

    easeOutBounce easing funct ion

    $(clickme)cl ick(function() $(book)animate( width toggle height toggle duration 5000 specialEasing width l inear height easeOutBounce complete function() $(this)after(ltdivgtAnimation completeltdivgt) ))

    As previously noted a plugin is required for the easeOutBounce funct ion

    Example 1 Click the button to animate the div with a number of dif ferent propert ies

    Javascript

    Using multiple unit types within one animation

    $(go)cl ick(function() $(block)animate( width 70 opacity 04 marginLeft 06in fontSize 3em borderWidth 10px 1500 ))

    HTML

    ltbutton id=gogtampraquo Runltbuttongt

    ltdiv id=blockgtHelloltdivgt

    CSS

    div background-colorbcawidth100pxborder1px solid green

    Example 2 Animates a divs lef t property with a relat ive value Click several t imes on thebuttons to see the relat ive animat ions queued up

    Javascript

    $(right)cl ick(function() $(block)animate(left +=50px slow))

    $(left)cl ick(function() $(block)animate(left -=50px slow))

    HTML

    ltbutton id=leftgtamplaquoltbuttongt ltbutton id=rightgtampraquoltbuttongtltdiv class=blockgtltdivgt

    CSS

    div positionabsolute background-colorabc left50px width90px height90px margin5px

    Example 3 The f irst but ton shows how an unqueued animat ion works It expands the div out to90 width while the font-size is increasing Once the font-size change is complete the borderanimat ion will begin The second button starts a t radit ional chained animat ion where eachanimat ion will start once the previous animat ion on the element has completed

    Javascript

    $( go1 )cl ick(function() $( block1 )animate( width 90 queue false duration 3000 ) animate( fontSize 24px 1500 ) animate( borderRightWidth 15px 1500 ))

    $( go2 )cl ick(function() $( block2 )animate( width 90 1000 ) animate( fontSize 24px 1000 ) animate( borderLeftWidth 15px 1000 ))

    $( go3 )cl ick(function() $( go1 )add( go2 )cl ick())

    $( go4 )cl ick(function() $( div )css( width fontSize borderWidth ))

    HTML

    ltbutton id=go1gtampraquo Animate Block1ltbuttongtltbutton id=go2gtampraquo Animate Block2ltbuttongtltbutton id=go3gtampraquo Animate Bothltbuttongt

    ltbutton id=go4gtampraquo Resetltbuttongtltdiv id=block1gtBlock1ltdivgtltdiv id=block2gtBlock2ltdivgt

    CSS

    div background-colorbca width200px height11em text-aligncenter border2px solid green margin3px font-size14pxbutton font-size14px

    Example 4 Animates the f irst divs lef t property and synchronizes the remaining divs using thestep funct ion to set their lef t propert ies at each stage of the animat ion

    Javascript

    $( go )cl ick(function() $( blockfirst )animate( left 100 duration 1000 step function( now fx ) $( blockgt(0) )css( left now ) ))

    CSS

    div position relative background-color abc width 40px height 40px float left margin 5px

    HTML

    ltpgtltbutton id=gogtRun Acircraquoltbuttongtltpgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgt

    Example 5 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

    Javascript

    $( p )animate( height toggle opacity toggle slow )

    Example 6 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds

    Javascript

    $( p )animate( left 50 opacity 1 500 )

    Example 7 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion Note this code will donothing unless the paragraph element is hidden

    Javascript

    $( p )animate( opacity show slow easein )

    Example 8 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

    Javascript

    $( p )animate( height toggle opacity toggle duration slow )

    Example 9 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds It also will do it outside the queue meaning itwill automat ically start without wait ing for its turn

    Javascript

    $( p )animate( left 50px opacity 1 duration 500 queue false )

    Example 10 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion

    Javascript

    $( p )animate( opacity show duration slow easing easein )

    Example 11 An example of using a callback funct ion The f irst argument is an array of CSSpropert ies the second specif ies that the animat ion should take 1000 milliseconds to completethe third states the easing type and the fourth argument is an anonymous callback funct ion

    Javascript

    $( p )animate( height200 width400 opacity 5 1000 l inear function() alert(all done) )

    fadeTo

    Adjust the opacity of the matched elements

    Added in version 143

    fadeTo(durat ion opacity easing callback)jQuery

    durat ionStringNumber A string or number determining how long the animat ion will run

    opacityNumber A number between 0 and 1 denot ing the target opacity

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The fadeTo() method animates the opacity of the matched elements

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied the default durat ion of 400 milliseconds is usedUnlike the other ef fect methods fadeTo() requires that durat ion be explicit ly specif ied

    If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly shown we can dim it slowly $(clickme)cl ick(function() $(book)fadeTo(slow 05 function() Animation complete ) )

    With durat ion set to 0 this method just changes the opacity CSSproperty so fadeTo(0 opacity) is the same as css(opacity opacity)

    Example 1 Animates f irst paragraph to fade to an opacity of 033 (33about one third visible) complet ing the animat ion within 600milliseconds

    Javascript

    $(pfirst)cl ick(function () $(this)fadeTo(slow 033))

    HTML

    ltpgtClick this paragraph to see it fadeltpgt

    ltpgtCompare to this one that wont fadeltpgt

    Example 2 Fade div to a random opacity on each click complet ing theanimat ion within 200 milliseconds

    Javascript

    $(div)cl ick(function () $(this)fadeTo(fast Mathrandom()))

    CSS

    p width80px margin0 padding5px div width40px height40px positionabsolute divone top0 left0 backgroundf00 divtwo top20px left20px background0f0 divthree top40px left40px background00f

    HTML

    ltpgtAnd this is the l ibrary that John builtltpgt

    ltdiv id=onegtltdivgtltdiv id=twogtltdivgtltdiv id=threegtltdivgt

    Example 3 Find the right answer The fade will take 250 milliseconds andchange various styles when it completes

    Javascript

    var getPos = function (n) return (Mathfloor(n) 90) + px$(p)each(function (n) var r = Mathfloor(Mathrandom() 3)var tmp = $(this)text()$(this)text($(peq( + r + ))text())$(peq( + r + ))text(tmp)$(this)css(left getPos(n)))$(div)each(function (n) $(this)css(left getPos(n)) )css(cursor pointer)cl ick(function () $(this)fadeTo(250 025 function () $(this)css(cursor ) prev()css(font-weight bolder font-style ital ic) ) )

    CSS

    div p width80px height40px top0 margin0 positionabsolute padding-top8px p backgroundfcc text-aligncenter div backgroundblue

    HTML

    ltpgtWrongltpgtltdivgtltdivgtltpgtWrongltpgtltdivgtltdivgt

    ltpgtRightltpgtltdivgtltdivgt

    fadeOut

    Hide the matched elements by fading them to t ransparent

    Added in version 143

    fadeOut(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The fadeOut() method animates the opacity of the matched elements Once the opacityreaches 0 the display style property is set to none so the element no longer af fects the layoutof the page

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

    With the element init ially shown we can hide it slowly

    $(clickme)cl ick(function() $(book)fadeOut(slow function() Animation complete ))

    Note To avoid unnecessary DOM manipulation fadeOut() willnot hide an element that is already considered hidden Forinformation on which elements jQuery considers hidden seehidden Selector

    Easing

    As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

    As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

    Example 1 Animates all paragraphs to fade out complet ing theanimat ion within 600 milliseconds

    Javascript

    $(p)cl ick(function () $(p)fadeOut(slow) )

    CSS

    p font-size150 cursorpointer

    HTML

    ltpgt If you click on this paragraph youl l see it just fade away ltpgt

    Example 2 Fades out spans in one sect ion that you click on

    Javascript

    $(span)cl ick(function () $(this)fadeOut(1000 function () $(div)text( + $(this)text() + has faded) $(this)remove() ) ) $(span)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

    CSS

    span cursorpointer spanhil ite backgroundyellow div displayinline colorred

    HTML

    lth3gtFind the modifiers - ltdivgtltdivgtlth3gt ltpgt If you ltspangtreallyltspangt want to go outside ltspangtin the coldltspangt then make sure to wear your ltspangtwarmltspangt jacket given to you by your ltspangtfavoriteltspangt teacher ltpgt

    Example 3 Fades out two divs one with a linear easing and one with the default swingeasing

    Javascript

    $(btn1)cl ick(function() function complete() $(ltdivgt)text(thisid)appendTo(log) $(box1)fadeOut(1600 l inear complete) $(box2)fadeOut(1600 complete))

    $(btn2)cl ick(function() $(div)show() $(log)empty())

    CSS

    boxbutton floatleft margin5px 10px 5px 0 box height80px width80px background090 log clearleft

    HTML

    ltbutton id=btn1gtfade outltbuttongtltbutton id=btn2gtshowltbuttongt

    ltdiv id=loggtltdivgt

    ltdiv id=box1 class=boxgtlinearltdivgtltdiv id=box2 class=boxgtswingltdivgt

    fadeIn

    Display the matched elements by fading them to opaque

    Added in version 143

    fadeIn(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The fadeIn() method animates the opacity of the matched elements

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly hidden we can show it slowly $(clickme)cl ick(function() $(book)fadeIn(slow function() Animation complete ) )

    Easing

    As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

    As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

    Example 1 Animates hidden divs to fade in one by one complet ing eachanimat ion within 600 milliseconds

    Javascript

    $(documentbody)cl ick(function () $(divhiddenfirst)fadeIn(slow) )

    CSS

    span colorred cursorpointer div margin3px width80px displaynone height80px floatleft divone backgroundf00 divtwo background0f0 divthree background00f

    HTML

    ltspangtClick hereltspangt

    ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt

    Example 2 Fades a red block in over the text Once the animat ion is done it quickly fades inmore text on top

    Javascript

    $(a)cl ick(function () $(div)fadeIn(3000 function () $(span)fadeIn(100) ) return false )

    CSS

    p positionrelative width400px height90px div positionabsolute width400px height65px font-size36px text-aligncenter coloryellow backgroundred padding-top25px top0 left0 displaynone span displaynone

    HTML

    ltpgt 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 (lta href=gtclickltagt) ltdivgtltspangtCENSOREDltspangtltdivgt

    ltpgt

    slideToggle

    Display or hide the matched elements with a sliding mot ion

    Added in version 143

    slideToggle(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The slideToggle() method animates the height of the matched elements This causes lowerparts of the page to slide up or down appearing to reveal or conceal the items If the element isinit ially displayed it will be hidden if hidden it will be shown The display property is saved andrestored as needed If an element has a display value of inline then is hidden and shown it willonce again be displayed inline When the height reaches 0 af ter a hiding animat ion the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster ones

    The strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

    We will cause slideToggle() to be called when another element is clicked

    $(clickme)cl ick(function() $(book)sl ideToggle(slow function() Animation complete ))

    With the element init ially shown we can hide it slowly with the f irst click

    A second click will show the element once again

    Easing

    As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

    As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed their

    animat ions ( See the example for promise() )

    Example 1 Animates all paragraphs to slide up or down complet ing theanimat ion within 600 milliseconds

    Javascript

    $(button)cl ick(function () $(p)sl ideToggle(slow) )

    CSS

    p width400px

    HTML

    ltbuttongtToggleltbuttongt

    ltpgt This is the paragraph to end all paragraphs You should feel ltemgtluckyltemgt to have seen such a paragraph in your l i fe Congratulations ltpgt

    Example 2 Animates divs between dividers with a toggle that makessome appear and some disappear

    Javascript

    $(aa)cl ick(function () $(divnot(sti l l))sl ideToggle(slow function () var n = parseInt($(span)text() 10) $(span)text(n + 1) ) )

    CSS

    div backgroundb977d1 margin3px width60px height60px floatleft divsti l l background345 width5px divhider displaynone span colorred p clear left

    HTML

    ltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv style=displaynonegtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltpgtltbutton id=aagtToggleltbuttongt There have been ltspangt0ltspangt toggled divsltpgt

    slideUp

    Hide the matched elements with a sliding mot ion

    Added in version 143

    slideUp(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The slideUp() method animates the height of the matched elements This causes lower partsof the page to slide up appearing to conceal the items Once the height reaches 0 the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

    With the element init ially shown we can hide it slowly

    $(clickme)cl ick(function() $(book)sl ideUp(slow function() Animation complete ))

    Easing

    As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

    As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

    Example 1 Animates all divs to slide up complet ing the animat ion within400 milliseconds

    Javascript

    $(documentbody)cl ick(function () i f ($(divfirst)is(hidden)) $(div)show(slow) else $(div)sl ideUp() )

    CSS

    div background3d9a44 margin3px width80px height40px floatleft

    HTML

    Click me ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

    ltdivgtltdivgt

    Example 2 Animates the parent paragraph to slide up complet ing the animat ion within 200milliseconds Once the animat ion is done it displays an alert

    Javascript

    $(button)cl ick(function () $(this)parent()sl ideUp(slow function () $(msg)text($(button this)text() + has completed) ) )

    CSS

    div margin2px

    HTML

    ltdivgt ltbuttongtHide Oneltbuttongt ltinput type=text value=One gt

    ltdivgtltdivgt ltbuttongtHide Twoltbuttongt ltinput type=text value=Two gt

    ltdivgtltdivgt ltbuttongtHide Threeltbuttongt ltinput type=text value=Three gt

    ltdivgtltdiv id=msggtltdivgt

    slideDown

    Display the matched elements with a sliding mot ion

    Added in version 143

    slideDown(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    The slideDown() method animates the height of the matched elements This causes lowerparts of the page to slide down making way for the revealed items

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

    With the element init ially hidden we can show it slowly

    $(clickme)cl ick(function() $(book)sl ideDown(slow function() Animation complete ))

    Easing

    As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

    Callback Function

    If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

    As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

    Example 1 Animates all divs to slide down and show themselves over600 milliseconds

    Javascript

    $(documentbody)cl ick(function () if ($(divfirst)is(hidden)) $(div)sl ideDown(slow) else $(div)hide())

    CSS

    div backgroundde9a44 margin3px width80px height40px displaynone floatleft

    HTML

    Click meltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

    Example 2 Animates all inputs to slide down complet ing the animat ion within 1000milliseconds Once the animat ion is done the input look is changed especially if it is the middleinput which gets the focus

    Javascript

    $(div)cl ick(function () $(this)css( borderStyleinset cursorwait )$(input)sl ideDown(1000function()$(this)css(border 2px red inset)fi lter(middle) css(background yellow) focus()$(div)css(visibil ity hidden)))

    CSS

    div backgroundcfd margin3px width50px text-aligncenter floatleft cursorpointerborder2px outset black font-weightbolder input displaynone width120px floatleft margin10px

    HTML

    ltdivgtPushltdivgtltinput type=text gtltinput type=text class=middle gt

    ltinput type=text gt

    toggle

    Display or hide the matched elements

    Added in version 13

    toggle(showOrHide)jQuery

    showOrHideBoolean A Boolean indicat ing whether to show or hide the elements

    With no parameters the toggle() method simply toggles the visibility of elements

    $(target)toggle()

    The matched elements will be revealed or hidden immediately with no animat ion by changingthe CSS display property If the element is init ially displayed it will be hidden if hidden it will beshown The display property is saved and restored as needed If an element has a display valueof inline then is hidden and shown it will once again be displayed inline

    When a durat ion is provided toggle() becomes an animat ion method The toggle() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 af ter a hiding animat ion the display style property is set to none to ensurethat the element no longer af fects the layout of the page

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    Note The event handling suite also has a method named toggle() Which one isfired depends on the set of arguments passed

    As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use of

    plug-ins most notably the jQuery UI suite

    If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

    We will cause toggle() to be called when another element is clicked

    $(clickme)cl ick(function() $(book)toggle(slow function() Animation complete ))

    With the element init ially shown we can hide it slowly with the f irst click

    A second click will show the element once again

    The second version of the method accepts a Boolean parameter If thisparameter is t rue then the matched elements are shown if false theelements are hidden In essence the statement

    $(foo)toggle(showOrHide)

    is equivalent to

    i f ( showOrHide == true ) $(foo)show() else if ( showOrHide == false ) $(foo)hide()

    Example 1 Toggles all paragraphs

    Javascript

    $(button)cl ick(function () $(p)toggle())

    HTML

    ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

    Example 2 Animates all paragraphs to be shown if they are hidden andhidden if they are visible complet ing the animat ion within 600milliseconds

    Javascript

    $(button)cl ick(function () $(p)toggle(slow))

    CSS

    p backgrounddadfont-weightboldfont-size16px

    HTML

    ltbuttongtToggle emltbuttongt

    ltpgtHiyaltpgtltpgtSuch interesting text ehltpgt

    Example 3 Shows all paragraphs then hides them all back and forth

    Javascript

    var fl ip = 0$(button)cl ick(function () $(p)toggle( fl ip++ 2 == 0 ))

    HTML

    ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

    hide

    Hide the matched elements

    Added in version 143

    hide(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determininghow long the animat ion will run

    easingString (opt ional) A string indicat ing whicheasing funct ion to use for the t ransit ion

    callbackCallback (opt ional) A funct ion to call once theanimat ion is complete

    With no parameters the hide() method is the simplest way to hide an element

    $(target)hide()

    The matched elements will be hidden immediately with no animat ion This is roughly equivalentto calling css(display none) except that the value of the display property is saved in jQuerysdata cache so that display can later be restored to its init ial value If an element has a displayvalue of inline then is hidden and shown it will once again be displayed inline

    When a durat ion is provided hide() becomes an animat ion method The hide() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 the display style property is set to none to ensure that the element nolonger af fects the layout of the page

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

    If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly shown we can hide it slowly$(clickme)cl ick(function() $(book)hide(slow function() alert(Animation complete) ))

    Example 1 Hides all paragraphs then the link on click

    Javascript

    $(p)hide() $(a)cl ick(function ( event ) eventpreventDefault() $(this)hide() )

    HTML

    ltpgtHelloltpgt lta href=gtClick to hide me tooltagt ltpgtHere is another paragraphltpgt

    Example 2 Animates all shown paragraphs to hide slowly complet ingthe animat ion within 600 milliseconds

    Javascript

    $(button)cl ick(function () $(p)hide(slow) )

    CSS

    p backgrounddad font-weightbold

    HTML

    ltbuttongtHide emltbuttongt

    ltpgtHiyaltpgt ltpgtSuch interesting text ehltpgt

    Example 3 Animates all spans (words in this case) to hide fast ly complet ing each animat ionwithin 200 milliseconds Once each animat ion is done it starts the next one

    Javascript

    $(hidr)cl ick(function () $(spanlast-child)hide(fast function () use callee so dont have to name the function $(this)prev()hide(fast argumentscallee) ) ) $(showr)cl ick(function () $(span)show(2000) )

    CSS

    span backgrounddef3ca padding3px floatleft

    HTML

    ltbutton id=hidrgtHideltbuttongt ltbutton id=showrgtShowltbuttongt ltdivgt

    ltspangtOnceltspangt ltspangtuponltspangt ltspangtaltspangt ltspangttimeltspangt ltspangtthereltspangt ltspangtwereltspangt ltspangtthreeltspangt ltspangtprogrammersltspangt

    ltdivgt

    Example 4 Hides the divs when clicked over 2 seconds then removes the div element when itshidden Try clicking on more than one box at a t ime

    Javascript

    for (var i = 0 i lt 5 i++) $(ltdivgt)appendTo(documentbody) $(div)cl ick(function () $(this)hide(2000 function () $(this)remove() ) )

    CSS

    div backgroundece023 width30px height40px margin2px floatleft

    HTML

    ltdivgtltdivgt

    show

    Display the matched elements

    Added in version 143

    show(durat ion easing callback)jQuery

    durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

    easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

    callbackCallback (opt ional) A funct ion to call once the animat ion is complete

    With no parameters the show() method is the simplest way to display an element

    $(target)show()

    The matched elements will be revealed immediately with no animat ion This is roughlyequivalent to calling css(display block) except that the display property is restored towhatever it was init ially If an element has a display value of inline then is hidden and shown itwill once again be displayed inline

    Note If using important in your styles such as display none important it is necessary tooverride the style using css(display block important ) should you wish for show() to funct ioncorrect ly

    When a durat ion is provided show() becomes an animat ion method The show() methodanimates the width height and opacity of the matched elements simultaneously

    Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

    As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

    If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

    We can animate any element such as a simple image

    ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly hidden we can show it slowly$(clickme)cl ick(function() $(book)show(slow function() Animation complete ))

    Example 1 Animates all hidden paragraphs to show slowly complet ingthe animat ion within 600 milliseconds

    Javascript

    $(button)cl ick(function () $(p)show(slow) )

    CSS

    p backgroundyellow

    HTML

    ltbuttongtShow itltbuttongt

    ltp style=display nonegtHello 2ltpgt

    Example 2 Animates all hidden divs to show fast ly in order complet ingeach animat ion within 200 milliseconds Once each animat ion is done itstarts the next one

    Javascript

    $(showr)cl ick(function () $(diveq(0))show(fast function () use callee so dont have to name the function $(this)next(div)show(fast argumentscallee) ))$(hidr)cl ick(function () $(div)hide(2000))

    CSS

    div backgrounddef3ca margin3px width80px displaynone floatleft text-aligncenter

    HTML

    ltbutton id=showrgtShowltbuttongt ltbutton id=hidrgtHideltbuttongt ltdivgtHello 3ltdivgt

    ltdivgthowltdivgt ltdivgtareltdivgt ltdivgtyoultdivgt

    Example 3 Shows all span and input elements with an animat ion Once the animat ion is done itchanges the text

    Javascript

    function doIt() $(spandiv)show(slow) can pass in function name $(button)cl ick(doIt)

    $(form)submit(function () if ($(input)val() == yes) $(p)show(4000 function () $(this)text(Ok DONE (now showing)) ) $(spandiv)hide(fast) to stop the submit return false )

    CSS

    span displaynone div displaynone p font-weightbold background-colorfcd

    HTML

    ltbuttongtDo itltbuttongt ltspangtAre you sure (type yes if you are) ltspangt ltdivgt ltformgt ltinput type=text value=asldkfjalsdfgt ltformgt ltdivgt ltp style=displaynonegtIm hiddenltpgt

    Ajax

    jQueryajaxPrefilter

    Handle custom Ajax opt ions or modify exist ing opt ions before each request is sent and beforethey are processed by $ajax()

    Added in version 15

    jQueryajaxPref ilter(dataTypes handler(opt ions originalOpt ions jqXHR))undef ined

    dataTypesString (opt ional) An opt ional string containing one or more

    space-separated dataTypes

    handler(opt ionsoriginalOpt ionsjqXHR)Funct ion

    A handler to set default values for future Ajaxrequests

    A typical pref ilter registrat ion using $ajaxPref ilter() looks like this

    $ajaxPrefi lter( function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

    where

    opt ions are the request opt ions

    originalOpt ions are the opt ions as provided to the ajax method unmodif ied and thuswithout defaults f rom ajaxSett ings

    jqXHR is the jqXHR object of the request

    Pref ilters are a perfect f it when custom opt ions need to be handled Given the following codefor example a call to $ajax() would automat ically abort a request to the same URL if thecustom abortOnRetry opt ion is set to t rue

    var currentRequests =

    $ajaxPrefi lter(function( options originalOptions jqXHR ) if ( optionsabortOnRetry ) i f ( currentRequests[ optionsurl ] ) currentRequests[ optionsurl ]abort() currentRequests[ optionsurl ] = jqXHR )

    Pref ilters can also be used to modify exist ing opt ions For example the following proxies cross-domain requests through ht tpmydomainnetproxy

    $ajaxPrefi lter( function( options ) if ( optionscrossDomain ) optionsurl = httpmydomainnetproxy + encodeURIComponent( optionsurl ) optionscrossDomain = false )

    If the opt ional dataTypes argument is supplied the pref ilter will be only be applied to requestswith the indicated dataTypes For example the following only applies the given pref ilter toJSON and script requests

    $ajaxPrefi lter( json script function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

    The $ajaxPref ilter() method can also redirect a request to another dataType by returning thatdataType For example the following sets a request as script if the URL has some specif icpropert ies def ined in a custom isActuallyScript() funct ion

    $ajaxPrefi lter(function( options ) if ( isActuallyScript( optionsurl ) ) return script )

    This would ensure not only that the request is considered script but also that all the pref iltersspecif ically at tached to the script dataType would be applied to it

    ajaxComplete

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

    Added in version 10

    ajaxComplete(handler(event XMLHttpRequest ajaxOpt ions))jQuery

    handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

    Whenever an Ajax request completes jQuery t riggers the ajaxComplete event Any and allhandlers that have been registered with the ajaxComplete() method are executed at this t ime

    To observe this method in act ion we can set up a basic Ajax load request

    ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

    When the user clicks the button and the Ajax request completes the log message is displayed

    Note Because ajaxComplete() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

    All ajaxComplete handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxComplete handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

    Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

    $(log)ajaxComplete(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxComplete handler The result is + xhrresponseHTML) )

    Example 1 Show a message when an Ajax request completes

    Javascript

    $(msg)ajaxComplete(function(eventrequest settings) $(this)append(ltligtRequest Completeltl igt) )

    serializeArray see Forms

    serialize see Forms

    jQueryajaxSetup

    Set default values for future Ajax requests

    Added in version 11

    jQueryajaxSetup(opt ions)

    opt ionsOpt ions A set of keyvalue pairs that conf igure the default Ajax request Allopt ions are opt ional

    For details on the sett ings available for $ajaxSetup() see $ajax()

    All subsequent Ajax calls using any funct ion will use the new sett ings unless overridden by theindividual calls unt il the next invocat ion of $ajaxSetup()

    For example the following sets a default for the url parameter before pinging the serverrepeatedly

    $ajaxSetup( url pingphp)

    Now each t ime an Ajax request is made the pingphp URL will be used automat ically

    $ajax( url not set here uses pingphp data name Dan)

    Note Global callback functions should be set with their respective global Ajaxevent handler methodsacirceurordquoajaxStart() ajaxStop() ajaxComplete() ajaxError()ajaxSuccess() ajaxSend()acirceurordquorather than within the options object for$ajaxSetup()

    Example 1 Sets the defaults for Ajax requests to the url xmlht tp disables global handlersand uses POST instead of GET The following Ajax requests then sends some data withouthaving to set anything else

    Javascript

    $ajaxSetup( url xmlhttp global false type POST

    ) $ajax( data myData )

    ajaxSuccess

    Attach a funct ion to be executed whenever an Ajax request completes successfully This is anAjax Event

    Added in version 10

    ajaxSuccess(handler(event XMLHttpRequest ajaxOpt ions))jQuery

    handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

    Whenever an Ajax request completes successfully jQuery t riggers the ajaxSuccess event Anyand all handlers that have been registered with the ajaxSuccess() method are executed at thist ime

    To observe this method in act ion we can set up a basic Ajax load request

    ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

    When the user clicks the button and the Ajax request completes successfully the log messageis displayed

    Note Because ajaxSuccess() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

    All ajaxSuccess handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxSuccess handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

    Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

    $(log)ajaxSuccess(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSuccess handler The ajax response was + xhrresponseHTML ) )

    Example 1 Show a message when an Ajax request completes successfully

    Javascript

    $(msg)ajaxSuccess(function(evt request settings) $(this)append(ltligtSuccessful Requestltl igt) )

    ajaxStop

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

    Added in version 10

    ajaxStop(handler())jQuery

    handler()Funct ion The funct ion to be invoked

    Whenever an Ajax request completes jQuery checks whether there are any other outstandingAjax requests If none remain jQuery t riggers the ajaxStop event Any and all handlers that havebeen registered with the ajaxStop() method are executed at this t ime The ajaxStop event isalso t riggered if the last outstanding Ajax request is cancelled by returning false within thebeforeSend callback funct ion

    To observe this method in act ion we can set up a basic Ajax load request

    ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

    When the user clicks the button and the Ajax request completes the log message is displayed

    Because ajaxStop() is implemented as a method of jQuery object instances we can use thethis keyword as we do here to refer to the selected elements within the callback funct ion

    Example 1 Hide a loading message af ter all the Ajax requests have stopped

    Javascript

    $(loading)ajaxStop(function() $(this)hide() )

    ajaxStart

    Register a handler to be called when the f irst Ajax request begins This is an Ajax Event

    Added in version 10

    ajaxStart(handler())jQuery

    handler()Funct ion The funct ion to be invoked

    Whenever an Ajax request is about to be sent jQuery checks whether there are any otheroutstanding Ajax requests If none are in progress jQuery t riggers the ajaxStart event Any andall handlers that have been registered with the ajaxStart() method are executed at this t ime

    To observe this method in act ion we can set up a basic Ajax load request

    ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

    When the user clicks the button and the Ajax request is sent the log message is displayed

    Note Because ajaxStart() is implemented as a method of jQuery object instances we can usethe this keyword as we do here to refer to the selected elements within the callback funct ion

    Example 1 Show a loading message whenever an Ajax request starts (and none is alreadyact ive)

    Javascript

    $(loading)ajaxStart(function() $(this)show() )

    ajaxSend

    Attach a funct ion to be executed before an Ajax request is sent This is an Ajax Event

    Added in version 10

    ajaxSend(handler(event jqXHR ajaxOpt ions))jQuery

    handler(event jqXHR ajaxOpt ions)Funct ion The funct ion to be invoked

    Whenever an Ajax request is about to be sent jQuery t riggers the ajaxSend event Any and allhandlers that have been registered with the ajaxSend() method are executed at this t ime

    To observe this method in act ion we can set up a basic Ajax load request

    ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

    When the user clicks the button and the Ajax request is about to begin the log message isdisplayed

    Note Because ajaxSend() is implemented as a method of jQuery instances we can use the thiskeyword as we do here to refer to the selected elements within the callback funct ion

    All ajaxSend handlers are invoked regardless of what Ajax request is to be sent If we mustdif ferent iate between the requests we can use the parameters passed to the handler Eacht ime an ajaxSend handler is executed it is passed the event object the jqXHR object (in version14 XMLHttpRequestobject) and the sett ings object that was used in the creat ion of the Ajaxrequest For example we can restrict our callback to only handling events dealing with apart icular URL

    $(log)ajaxSend(function(e jqxhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSend handler) )

    Example 1 Show a message before an Ajax request is sent

    Javascript

    $(msg)ajaxSend(function(evt request settings) $(this)append(ltligtStarting request at + settingsurl + ltl igt) )

    ajaxError

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

    Added in version 10

    ajaxError(handler(event jqXHR ajaxSett ings thrownError))jQuery

    handler(event jqXHR ajaxSett ings thrownError)Funct ion The funct ion to be invoked

    Whenever an Ajax request completes with an error jQuery t riggers the ajaxError event Any andall handlers that have been registered with the ajaxError() method are executed at this t ime

    To observe this method in act ion set up a basic Ajax load request

    ltbutton class=triggergtTriggerltbuttongtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

    Attach the event handler to any element

    $(divlog)ajaxError(function() $(this)text( Triggered ajaxError handler ))

    Now make an Ajax request using any jQuery method

    $(buttontrigger)cl ick(function() $(divresult)load( ajaxmissinghtml ))

    When the user clicks the button and the Ajax request fails because the requested f ile ismissing the log message is displayed

    Note Because ajaxError() is implemented as a method of jQuery object instances you can usethe this keyword within the callback funct ion to refer to the selected elements

    All ajaxError handlers are invoked regardless of what Ajax request was completed Todif ferent iate between the requests you can use the parameters passed to the handler Eacht ime an ajaxError handler is executed it is passed the event object the jqXHR object (prior tojQuery 15 the XHR object) and the sett ings object that was used in the creat ion of the

    request If the request failed because JavaScript raised an except ion the except ion object ispassed to the handler as a fourth parameter For example to restrict the error callback to onlyhandling events dealing with a part icular URL

    $( divlog )ajaxError(function(e jqxhr settings exception) if ( settingsurl == ajaxmissinghtml ) $(this)text( Triggered ajaxError handler ) )

    Example 1 Show a message when an Ajax request fails

    Javascript

    $(msg)ajaxError(function(event request settings) $(this)append(ltligtError requesting page + settingsurl + ltl igt))

    jQuerypost

    Load data f rom the server using a HTTP POST request

    Added in version 10

    jQuerypost(url data success(data textStatus jqXHR) dataType)jqXHR

    urlString A string containing the URL to which the request is sent

    dataMap String (opt ional) A map or string that is sent to the server with therequest

    success(datatextStatusjqXHR)Funct ion

    (opt ional) A callback funct ion that is executed if the requestsucceeds

    dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

    This is a shorthand Ajax funct ion which is equivalent to

    $ajax( type POST url url data data success success dataType dataType)

    The success callback funct ion is passed the returned data which will be an XML root elementor a text string depending on the MIME type of the response It is also passed the text statusof the response

    As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object)

    Most implementat ions will specify a success handler

    $post(ajaxtesthtml function(data) $( result)html(data))

    This example fetches the requested HTML snippet and inserts it on the page

    Pages fetched with POST are never cached so the cache and ifModif ied opt ions injQueryajaxSetup() have no ef fect on these requests

    The jqXHR Object

    As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $post() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

    The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $post() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

    Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $post(examplephp 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 jqxhrcomplete(function() alert(second complete) )

    Example 1 Request the test php page but ignore the return results

    Javascript

    $post(testphp)

    Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

    Javascript

    $post(testphp name John time 2pm )

    Example 3 pass arrays of data to the server (while st ill ignoring the return results)

    Javascript

    $post(testphp choices[] [ Jon Susan] )

    Example 4 send form data using ajax requests

    Javascript

    $post(testphp $(testform)serial ize())

    Example 5 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

    Javascript

    $post(testphp function(data) alert(Data Loaded + data) )

    Example 6 Alert out the results f rom request ing test php with an addit ional payload of data(HTML or XML depending on what was returned)

    Javascript

    $post(testphp name John time 2pm function(data) alert(Data Loaded + data) )

    Example 7 Gets the test php page content store it in a XMLHttpResponse object and appliesthe process() JavaScript funct ion

    Javascript

    $post(testphp name John time 2pm function(data) process(data) xml)

    Example 8 Posts to the test php page and gets contents which has been returned in jsonformat (Johnt ime=gt2pm)) gt)

    Javascript

    $post(testphp func getNameAndTime function(data) consolelog(dataname) John consolelog(datatime) 2pm json)

    Example 9 Post a form using ajax and put results in a div

    Javascript

    attach a submit handler to the form $(searchForm)submit(function(event)

    stop form from submitting normally eventpreventDefault() get some values from elements on the page var $form = $( this ) term = $formfind( input[name=s] )val() url = $formattr( 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 )empty()append( content ) ) )

    HTML

    ltform action= id=searchFormgt ltinput type=text name=s placeholder=Search gt ltinput type=submit value=Search gt ltformgt lt-- the result of the search wil l be rendered inside this div --gt ltdiv id=resultgtltdivgt

    jQuerygetScript

    Load a JavaScript f ile f rom the server using a GET HTTP request then execute it

    Added in version 10

    jQuerygetScript(url success(data textStatus))jqXHR

    urlString A string containing the URL to which the request is sent

    success(datatextStatus)Funct ion

    (opt ional) A callback funct ion that is executed if therequest succeeds

    This is a shorthand Ajax funct ion which is equivalent to

    $ajax( url url dataType script success success)

    The callback is passed the returned JavaScript f ile This is generally not useful as the script willalready have run at this point

    The script is executed in the global context so it can refer to other variables and use jQueryfunct ions Included scripts can have some impact on the current page

    $(result)html(ltpgtLorem ipsum dolor sit ametltpgt)

    Scripts are included and run by referencing the f ile name

    $getScript(ajaxtestjs function(data textStatus) consolelog(data) data returned consolelog(textStatus) success consolelog(Load was performed))

    Note Should you require an addit ional callback for errors when using the getScript() methodthe global ajaxError() callback event may be used to achieve this as follows

    $( divlog )ajaxError(function(e jqxhr settings exception) if (settingsdataType==script) $(this)text( Triggered ajaxError handler ) )

    Example 1 Load the of f icial jQuery Color Animat ion plugin dynamically and bind some coloranimat ions to occur once the new funct ionality is loaded

    Javascript

    $getScript(httpdevjquerycomviewtrunkpluginscolorjquerycolorjs function() $(go)cl ick(function() $(block)animate( backgroundColor pink 1000) delay(500) animate( backgroundColor blue 1000) ))

    HTML

    ltbutton id=gogtampraquo Runltbuttongt

    ltdiv class=blockgtltdivgt

    CSS

    block background-color blue width 150px height 70px margin 10px

    jQuerygetJSON

    Load JSON-encoded data f rom the server using a GET HTTP request

    Added in version 10

    jQuerygetJSON(url data success(data textStatus jqXHR))jqXHR

    urlString A string containing the URL to which the request issent

    dataMap (opt ional) A map or string that is sent to the serverwith the request

    success(data textStatusjqXHR)Funct ion

    (opt ional) A callback funct ion that is executed if therequest succeeds

    This is a shorthand Ajax funct ion which is equivalent to

    $ajax( url url dataType json data data success callback)

    Data that is sent to the server is appended to the URL as a query string If the value of the dataparameter is an object (map) it is converted to a string and url-encoded before it is appendedto the URL

    Most implementat ions will specify a success handler

    $getJSON(ajaxtestjson function(data) var items = []

    $each(data function(key val) itemspush(ltli id= + key + gt + val + ltl igt) )

    $(ltulgt class my-new-list html itemsjoin( ) )appendTo(body))

    This example of course relies on the structure of the JSON f ile

    one Singular sensation two Beady l ittle 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 success callback is passed the returned data which is typically a JavaScript object or arrayas def ined by the JSON structure and parsed using the $parseJSON() method It is also passedthe text status of the response

    As of jQuery 15 the success callback funct ion receives a jqXHR object (in jQuery 14 itreceived the XMLHttpRequest object) However since JSONP and cross-domain GET requestsdo not use XHR in those cases the jqXHR and textStatus parameters passed to the successcallback are undef ined

    Important As of jQuery 14 if the JSON file contains a syntax error the requestwill usually fail silently Avoid frequent hand-editing of JSON data for this reasonJSON is a data-interchange format with syntax rules that are stricter than those ofJavaScripts object literal notation For example all strings represented in JSONwhether they are properties or values must be enclosed in double-quotes Fordetails on the JSON format see httpjsonorg

    JSONP

    If the URL includes the string callback= (or similar as def ined by the server-side API) therequest is t reated as JSONP instead See the discussion of the jsonp data type in $ajax() for

    more details

    The jqXHR Object

    As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $getJSON() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

    The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $getJSON()to chain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

    Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $getJSON(examplejson 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 abovejqxhrcomplete(function() alert(second complete) )

    Example 1 Loads the four most recent cat pictures f rom the Flickr JSONP API

    Javascript

    $getJSON(httpapifl ickrcomservicesfeedsphotos_publicgnejsoncallback= tags cat tagmode any format json function(data) $each(dataitems function(iitem) $(ltimggt)attr(src itemmediam)appendTo(images) i f ( i == 3 ) return false ) )

    HTML

    ltdiv id=imagesgt

    ltdivgt

    CSS

    img height 100px float left

    Example 2 Load the JSON data f rom test js and access a name from the returned JSON data

    Javascript

    $getJSON(testjs function(json) alert(JSON Data + jsonusers[3]name) )

    Example 3 Load the JSON data f rom test js passing along addit ional data and access a namefrom the returned JSON data

    Javascript

    $getJSON(testjs name John time 2pm function(json) alert(JSON Data + jsonusers[3]name) )

    jQueryget

    Load data f rom the server using a HTTP GET request

    Added in version 10

    jQueryget(url data success(data textStatus jqXHR) dataType)jqXHR

    urlString A string containing the URL to which the request is sent

    dataMap String (opt ional) A map or string that is sent to the server with therequest

    success(datatextStatusjqXHR)Funct ion

    (opt ional) A callback funct ion that is executed if the requestsucceeds

    dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

    This is a shorthand Ajax funct ion which is equivalent to

    $ajax( url url data data success success dataType dataType)

    The success callback funct ion is passed the returned data which will be an XML root elementtext string JavaScript f ile or JSON object depending on the MIME type of the response It isalso passed the text status of the response

    As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object) However since JSONP and cross-domain GETrequests do not use XHR in those cases the (j)XHR and textStatus parameters passed to thesuccess callback are undef ined

    Most implementat ions will specify a success handler

    $get(ajaxtesthtml 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

    As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $get() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

    The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $get() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

    Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $get(examplephp 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 jqxhrcomplete(function() alert(second complete) )

    Example 1 Request the test php page but ignore the return results

    Javascript

    $get(testphp)

    Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

    Javascript

    $get(testphp name John time 2pm )

    Example 3 pass arrays of data to the server (while st ill ignoring the return results)

    Javascript

    $get(testphp choices[] [ Jon Susan] )

    Example 4 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

    Javascript

    $get(testphp function(data)alert(Data Loaded + data))

    Example 5 Alert out the results f rom request ing test cgi with an addit ional payload of data

    (HTML or XML depending on what was returned)

    Javascript

    $get(testcgi name John time 2pm function(data) alert(Data Loaded + data) )

    Example 6 Gets the test php page contents which has been returned in json format(Johnt ime=gt2pm)) gt) and adds it to the page

    Javascript

    $get(testphp function(data) $(body)append( Name + dataname ) John append( Time + datatime ) 2pm json)

    load

    Load data f rom the server and place the returned HTML into the matched element

    Added in version 10

    load(url data complete(responseText textStatus XMLHttpRequest))jQuery

    urlString A string containing the URL to which therequest is sent

    dataMap String A map or string that is sent to the server withthe request

    complete(responseText textStatusXMLHttpRequest)Funct ion

    (opt ional) A callback funct ion that is executedwhen the request completes

    This method is the simplest way to fetch data f rom the server It is roughly equivalent to$get(url data success) except that it is a method rather than global funct ion and it has animplicit callback funct ion When a successful response is detected (ie when textStatus issuccess or notmodif ied) load() sets the HTML contents of the matched element to thereturned data This means that most uses of the method can be quite simple

    $(result)load(ajaxtesthtml)

    The provided callback if any is executed af ter this post-processing has been performed

    $(result)load(ajaxtesthtml function() alert(Load was performed))

    In the two examples above if the current document does not contain an element with an ID ofresult the load() method is not executed

    The POST method is used if data is provided as an object otherwise GET is assumed

    Note The event handling suite also has a method named load() Which one isfired depends on the set of arguments passed

    Loading Page Fragments

    The load() method unlike $get() allows us to specify a port ion of the remote document to beinserted This is achieved with a special syntax for the url parameter If one or more spacecharacters are included in the string the port ion of the string following the f irst space isassumed 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(ajaxtesthtml container)

    When this method executes it retrieves the content of ajaxtest html but then jQuery parsesthe returned document to f ind the element with an ID of container This element along with itscontents is inserted into the element with an ID of result and the rest of the retrieveddocument is discarded

    jQuery uses the browsers innerHTML property to parse the retrieved document and insert itinto the current document During this process browsers of ten f ilter elements f rom thedocument such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements retrieved byload() may not be exact ly the same as if the document were retrieved direct ly by the browser

    Example 1 Load the main pages footer navigat ion into an ordered list

    Javascript

    $(new-nav)load( jq-footerNavigation l i)

    CSS

    body font-size 12px font-family Arial

    HTML

    ltbgtFooter navigationltbgtltol id=new-navgtltolgt

    Example 2 Display a not ice if the Ajax request encounters an error

    Javascript

    $(success)load(not-herephp function(response status xhr) if (status == error) var msg = Sorry but there was an error $(error)html(msg + xhrstatus + + xhrstatusText) )

    CSS

    body font-size 12px font-family Arial

    HTML

    ltbgtSuccessful Response (should be blank)ltbgtltdiv id=successgtltdivgtltbgtError Responseltbgtltdiv id=errorgtltdivgt

    Example 3 Load the feedshtml f ile into the div with the ID of feeds

    Javascript

    $(feeds)load(feedshtml)

    Results

    ltdiv id=feedsgtltbgt45ltbgt feeds foundltdivgt

    Example 4 pass arrays of data to the server

    Javascript

    $(objectID)load(testphp choices[] [ Jon Susan] )

    Example 5 Same as above but will POST the addit ional parameters to the server and acallback that is executed when the server is f inished responding

    Javascript

    $(feeds)load(feedsphp limit 25 function()alert(The last 25 entries in the feed have been loaded))

    jQueryajax

    Perform an asynchronous HTTP (Ajax) request

    Added in version 10

    jQueryajax(sett ings)jqXHR

    sett ingsMap A set of keyvalue pairs that conf igure the Ajax request All set t ings areopt ional A default can be set for any opt ion with $ajaxSetup()

    The $ajax() funct ion underlies all Ajax requests sent by jQuery It is of ten unnecessary todirect ly call this funct ion as several higher-level alternat ives like $get() and load() are availableand are easier to use If less common opt ions are required though $ajax() can be used moref lexibly

    At its simplest the $ajax() funct ion can be called with no arguments

    $ajax()

    Note Default set t ings can be set globally by using the $ajaxSetup() funct ion

    This example using no opt ions loads the contents of the current page but does nothing withthe result To use the result we can implement one of the callback funct ions

    The jqXHR Object

    The jQuery XMLHttpRequest (jqXHR) object returned by $ajax() as of jQuery 15 is a supersetof the browsers nat ive XMLHttpRequest object For example it contains responseText andresponseXML propert ies as well as a getResponseHeader() method When the transport

    mechanism is something other than XMLHttpRequest (for example a script tag for a JSONPrequest) the jqXHR object simulates nat ive XHR funct ionality where possible

    As of jQuery 151 the jqXHR object also contains the overrideMimeType() method (it wasavailable in jQuery 14x as well but was temporarily removed in jQuery 15) TheoverrideMimeType() method may be used in the beforeSend() callback funct ion for exampleto modify the response content-type header

    $ajax( url httpfiddlejshellnetfaviconpng beforeSend function( xhr ) xhroverrideMimeType( textplain charset=x-user-defined ) success function( data ) i f (console ampamp consolelog) consolelog( Sample of data datasl ice(0100) ) )

    The jqXHR objects returned by $ajax() as of jQuery 15 implement the Promise interface givingthem all the propert ies methods and behavior of a Promise (see Deferred object for moreinformat ion) For convenience and consistency with the callback names used by $ajax() jqXHRalso provides error() success() and complete() methods These methods take a funct ionargument that is called when the $ajax() request terminates and the funct ion receives thesame arguments as the correspondingly-named $ajax() callback This allows you to assignmult iple callbacks on a single request and even to assign callbacks af ter the request may havecompleted (If the request is already complete the callback is f ired immediately)

    Deprecation Notice The jqXHRsuccess() jqXHRerror() and jqXHRcomplete()callbacks will be deprecated in jQuery 18 To prepare your code for their eventualremoval use jqXHRdone() jqXHRfail() and jqXHRalways() instead

    Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $ajax( examplephp ) success(function() alert(success) ) error(function() alert(error) ) complete(function() alert(complete) )

    perform other work here

    Set another completion function for the request abovejqxhrcomplete(function() alert(second complete) )

    For backward compat ibility with XMLHttpRequest a jqXHR object will expose the followingpropert ies and methods

    readyState

    status

    statusText

    responseXML andor responseText when the underlying request responded with xmlandor text respect ively

    setRequestHeader(name value) which departs f rom the standard by replacing the oldvalue with the new one rather than concatenat ing the new value to the old one

    getAllResponseHeaders()

    getResponseHeader()

    abort()

    No onreadystatechange mechanism is provided however since success error complete andstatusCode cover all conceivable requirements

    Callback Function Queues

    The beforeSend error dataFilter success and complete opt ions all accept callback funct ionsthat are invoked at the appropriate t imes

    As of jQuery 15 the error (fail) success (done) and complete (always as of jQuery 16)callback hooks are f irst-in f irst-out managed queues This means you can assign more thanone callback for each hook See Deferred object methods which are implemented internally forthese $ajax() callback hooks

    The this reference within all callbacks is the object in the context opt ion passed to $ajax in thesett ings if context is not specif ied this is a reference to the Ajax sett ings themselves

    Some types of Ajax requests such as JSONP and cross-domain GET requests do not useXHR in those cases the XMLHttpRequest and textStatus parameters passed to the callbackare undef ined

    Here are the callback hooks provided by $ajax()

    1 beforeSend callback is invoked it receives the jqXHR object and the sett ings map asparameters

    2 error callbacks are invoked in the order they are registered if the request fails Theyreceive the jqXHR a string indicat ing the error type and an except ion object if applicableSome built -in errors will provide a string as the except ion object abort t imeout NoTransport

    3 dataFilter callback is invoked immediately upon successful receipt of response data Itreceives the returned data and the value of dataType and must return the (possiblyaltered) data to pass on to success

    4 success callbacks are then invoked in the order they are registered if the requestsucceeds They receive the returned data a string containing the success code and thejqXHR object

    5 complete callbacks f ire in the order they are registered when the request f inisheswhether in failure or success They receive the jqXHR object as well as a string containingthe success or error code

    For example to make use of the returned HTML we can implement a success handler

    $ajax( url ajaxtesthtml success function(data) $( result)html(data) alert(Load was performed) )

    Data Types

    The $ajax() funct ion relies on the server to provide informat ion about the retrieved data If theserver reports the return data as XML the result can be traversed using normal XML methodsor jQuerys selectors If another type is detected such as HTML in the example above the datais t reated as text

    Dif ferent data handling can be achieved by using the dataType opt ion Besides plain xml thedataType can be html json jsonp script or text

    The text and xml types return the data with no processing The data is simply passed on to thesuccess handler either through the responseText or responseXML property of the jqXHRobject respect ively

    Note We must ensure that the MIME type reported by the web server matches our choice ofdataType In part icular XML must be declared by the server as text xml or applicat ionxml forconsistent results

    If html is specif ied any embedded JavaScript inside the retrieved data is executed before theHTML is returned as a string Similarly script will execute the JavaScript that is pulled back fromthe server then return nothing

    The json type parses the fetched data f ile as a JavaScript object and returns the constructedobject as the result data To do so it uses jQueryparseJSON() when the browser supports it

    otherwise it uses a Funct ion constructor Malformed JSON data will throw a parse error (seejsonorg for more informat ion) JSON data is convenient for communicat ing structured data in away that is concise and easy for JavaScript to parse If the fetched data f ile exists on a remoteserver specify the jsonp type instead

    The jsonp type appends a query string parameter of callback= to the URL The server shouldprepend the JSON data with the callback name to form a valid JSONP response We canspecify a parameter name other than callback with the jsonp opt ion to $ajax()

    Note JSONP is an extension of the JSON format requiring some server-side code to detectand handle the query string parameter More informat ion about it can be found in the originalpost detailing its use

    When data is retrieved from remote servers (which is only possible using the script or jsonpdata types) the error callbacks and global events will never be f ired

    Sending Data to the Server

    By default Ajax requests are sent using the GET HTTP method If the POST method isrequired the method can be specif ied by sett ing a value for the type opt ion This opt ionaffects how the contents of the data opt ion are sent to the server POST data will always betransmit ted to the server using UTF-8 charset per the W3C XMLHTTPRequest standard

    The data opt ion can contain either a query string of the form key1=value1ampkey2=value2 or amap of the form key1 value1 key2 value2 If the lat ter form is used the data is convertedinto a query string using jQueryparam() before it is sent This processing can be circumventedby sett ing processData to false The processing might be undesirable if you wish to send anXML object to the server in this case change the contentType opt ion f rom applicat ionx-www-form-urlencoded to a more appropriate MIME type

    Advanced Options

    The global opt ion prevents handlers registered using ajaxSend() ajaxError() and similarmethods from f iring when this request would t rigger them This can be useful to for examplesuppress a loading indicator that was implemented with ajaxSend() if the requests are f requentand brief With cross-domain script and JSONP requests the global opt ion is automat ically setto false See the descript ions of these methods below for more details See the descript ions ofthese methods below for more details

    If the server performs HTTP authent icat ion before providing a response the user name andpassword pair can be sent via the username and password opt ions

    Ajax requests are t ime-limited so errors can be caught and handled to provide a better userexperience Request t imeouts are usually either lef t at their default or set as a global defaultusing $ajaxSetup() rather than being overridden for specif ic requests with the t imeout opt ion

    By default requests are always issued but the browser may serve results out of its cache Todisallow use of the cached results set cache to false To cause the request to report failure ifthe asset has not been modif ied since the last request set ifModif ied to t rue

    The scriptCharset allows the character set to be explicit ly specif ied for requests that use altscriptgt tag (that is a type of script or jsonp) This is useful if the script and host page havedif fering character sets

    The f irst let ter in Ajax stands for asynchronous meaning that the operat ion occurs in paralleland the order of complet ion is not guaranteed The async opt ion to $ajax() defaults to t rueindicat ing that code execut ion can cont inue af ter the request is made Sett ing this opt ion tofalse (and thus making the call no longer asynchronous) is strongly discouraged as it can causethe browser to become unresponsive

    The $ajax() funct ion returns the XMLHttpRequest object that it creates Normally jQueryhandles the creat ion of this object internally but a custom funct ion for manufacturing one canbe specif ied using the xhr opt ion The returned object can generally be discarded but doesprovide a lower-level interface for observing and manipulat ing the request In part icular callingabort() on the object will halt the request before it completes

    Extending Ajax

    As of jQuery 15 jQuerys Ajax implementat ion includes pref ilters converters and transportsthat allow you to extend Ajax with a great deal of f lexibility For more informat ion about theseadvanced features see the Extending Ajax page

    Example 1 Load and execute a JavaScript f ile

    Javascript

    $ajax( type GET url testjs dataType script )

    Example 2 Save some data to the server and not ify the user once it s complete

    Javascript

    $ajax( type POST url somephp data name=Johnamplocation=Boston success function(msg) alert( Data Saved + msg ) )

    Example 3 Retrieve the latest version of an HTML page

    Javascript

    $ajax( url testhtml cache false success function(html) $(results)append(html) )

    Example 4 Loads data synchronously Blocks the browser while the requests is act ive It isbetter to block user interact ion by other means when synchronizat ion is necessary

    Javascript

    var html = $ajax( url somephp async false )responseText

    Example 5 Sends an xml document as data to the server By sett ing the processData opt ion tofalse the automat ic conversion of data to strings is prevented

    Javascript

    var xmlDocument = [create xml document] $ajax( url pagephp processData false data xmlDocument success handleResponse )

    Example 6 Sends an id as data to the server save some data to the server and not ify the useronce it s complete Note that this usage - returning the result of the call into a variable -

    requires a synchronous (blocking) request (asyncfalse)

    Javascript

    var bodyContent = $ajax( url scriptphp global false type POST data id thisgetAttribute( id) dataType html asyncfalse success function(msg) alert(msg) )responseText

    jQueryparam see Forms

    Miscellaneous

    each see Traversing

    toArray

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

    Added in version 14

    toArray()Array

    toArray() returns all of the elements in the jQuery set

    alert($( l i )toArray())

    All of the matched DOM nodes are returned by this call contained in a standard array

    [ltli id=foogt ltli id=bargt]

    Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

    Javascript

    function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)toArray()reverse() )

    CSS

    span colorred

    HTML

    Reversed - ltspangtltspangt

    ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

    index

    Search for a given element f rom among the matched elements

    Added in version 10

    index(element)Number

    elementElementjQuery

    The DOM element or f irst element within the jQuery object tolook for

    Return Values

    If no argument is passed to the index() method the return value is an integer indicat ing theposit ion of the f irst element within the jQuery object relat ive to its sibling elements

    If index() is called on a collect ion of elements and a DOM element or jQuery object is passed inindex() returns an integer indicat ing the posit ion of the passed element relat ive to the originalcollect ion

    If a selector string is passed as an argument index() returns an integer indicat ing the posit ionof the original element relat ive to the elements matched by the selector If the element is notfound index() will return -1

    Detail

    The complementary operat ion to get() which accepts an index and returns a DOM nodeindex() can take a DOM node and returns an index Suppose we have a simple unordered list onthe page

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgt

    If we retrieve one of the three list items (for example through a DOM funct ion or as thecontext to an event handler) index() can search for this list item within the set of matchedelements

    var l istItem = documentgetElementById(bar)alert( Index + $( l i )index(l istItem))We get back the zero-based position of the l ist item

    Index 1

    Similarly if we retrieve a jQuery object consist ing of one of the three list items index() willsearch for that list item

    var l istItem = $(bar)alert( Index + $( l i )index(l istItem))

    We get back the zero-based posit ion of the list item

    Index 1

    Note that if the jQuery collect ion used as the index() methods argument contains more thanone element the f irst element within the matched set of elements will be used

    var l istItems = $( l i gt(0))alert( Index + $( l i )index(l istItems))

    We get back the zero-based posit ion of the f irst list item within the matched set

    Index 1

    If we use a string as the index() methods argument it is interpreted as a jQuery selector string

    The f irst element among the object s matched elements which also matches this selector islocated

    var l istItem = $(bar)alert( Index + l istItemindex( l i ))

    We get back the zero-based posit ion of the list item

    Index 1

    If we omit the argument index() will return the posit ion of the f irst element within the set ofmatched elements in relat ion to its siblings

    alert( Index + $(bar)index()

    Again we get back the zero-based posit ion of the list item

    Index 1

    Example 1 On click returns the index (based zero) of that div in the page

    Javascript

    $(div)cl ick(function () this is the dom element cl icked var index = $(div)index(this) $(span)text(That was div index + index))

    CSS

    div backgroundyellow margin5px span colorred

    HTML

    ltspangtClick a divltspangtltdivgtFirst divltdivgtltdivgtSecond divltdivgtltdivgtThird divltdivgt

    Example 2 Returns the index for the element with ID bar

    CSS

    div font-weight bold color 090

    Javascript

    var l istItem = $(bar) $(div)html( Index + $( l i )index(l istItem) )

    HTML

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

    Example 3 Returns the index for the f irst item in the jQuery collect ion

    CSS

    div font-weight bold color 090

    Javascript

    var l istItems = $( l i gt(0))$(div)html( Index + $( l i )index(l istItems) )

    HTML

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

    Example 4 Returns the index for the element with ID bar in relat ion to all

    elements

    CSS

    div font-weight bold color 090

    Javascript

    $(div)html( Index + $(bar)index( l i ) )

    HTML

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

    Example 5 Returns the index for the element with ID bar in relat ion to its siblings

    CSS

    div font-weight bold color 090

    Javascript

    var barIndex = $(bar)index()$(div)html( Index + barIndex )

    HTML

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

    Example 6 Returns -1 as there is no element with ID foobar

    CSS

    div font-weight bold color 090

    Javascript

    var foobar = $(l i)index( $(foobar) )$(div)html( Index + foobar)

    HTML

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

    removeData see Data

    data see Data

    data see Data

    get

    Retrieve the DOM elements matched by the jQuery object

    Added in version 10

    get(index)Element Array

    indexNumber (opt ional) A zero-based integer indicat ing which element to retrieve

    The get() method grants us access to the DOM nodes underlying each jQuery object Supposewe had a simple unordered list on the page

    ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligtltulgt

    Without a parameter get() returns all of the elements

    alert($( l i )get())

    All of the matched DOM nodes are returned by this call contained in a standard array

    [ltli id=foogt ltli id=bargt]

    With an index specif ied get() will retrieve a single element

    ($( l i )get(0))

    Since the index is zero-based the f irst list item is returned

    ltli id=foogt

    Each jQuery object also masquerades as an array so we can use the array dereferencingoperator to get at the list item instead

    alert($( l i )[0])

    However this syntax lacks some of the addit ional capabilit ies of get() such as specifying anegat ive index

    alert($( l i )get(-1))

    A negat ive index is counted from the end of the matched set so this example will return thelast item in the list

    ltli id=bargt

    Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

    Javascript

    function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)get()reverse() )

    CSS

    span colorred

    HTML

    Reversed - ltspangtltspangt

    ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

    Example 2 Gives the tag name of the element clicked on

    Javascript

    $( documentbody)cl ick(function (e) estopPropagation() var domEl = $(this)get(0) $(spanfirst)text(Clicked on - + domEltagName) )

    CSS

    span colorred div backgroundyellow

    HTML

    ltspangtampnbspltspangt ltpgtIn this paragraph is an ltspangtimportantltspangt sectionltpgt

    ltdivgtltinput type=text gtltdivgt

    size

    Return the number of elements in the jQuery object

    Added in version 10

    size()Number

    The size() method is funct ionally equivalent to the length property however the lengthproperty is preferred because it does not have the overhead of a funct ion call

    Given a simple unordered list on the page

    ltulgt ltligtfooltligt ltligtbarltligtltulgt

    Both size() and length ident ify the number of items

    alert( Size + $(l i)size() )alert( Size + $(l i)length )

    This results in two alerts

    Size 2

    Size 2

    Example 1 Count the divs Click to add more

    Javascript

    $(documentbody)cl ick(function() $(this)append( $(ltdivgt) ) var n = $(div)size() $(span)text(There are + n + divs Click to add more)) trigger the cl ick to startcl ick()

    CSS

    body cursorpointer min-height 100px div width50px height30px margin5px floatleft backgroundblue span colorred

    HTML

    ltspangtltspangt ltdivgtltdivgt

    jQuerynoConflict see Core

    jQueryparam see Forms

    Dimensions

    outerWidth see CSS

    outerHeight see CSS

    innerWidth see CSS

    innerHeight see CSS

    width see CSS

    width see CSS

    height see CSS

    height see CSS

    Offset

    offsetParent see Traversing

    scrollLeft see CSS

    scrollLeft see CSS

    scrollTop see CSS

    scrollTop see CSS

    position see CSS

    offset see CSS

    offset see CSS

    Utilities

    jQuerynow

    Return a number represent ing the current t ime

    Added in version 143

    jQuerynow()Number

    The $now() method is a shorthand for the number returned by the expression (newDate)getTime()

    jQueryparseXML

    Parses a string into an XML document

    Added in version 15

    jQueryparseXML(data)XMLDocument

    dataString a well-formed XML string to be parsed

    jQueryparseXML uses the nat ive parsing funct ion of the browser to create a valid XMLDocument This document can then be passed to jQuery to create a typical jQuery object thatcan be traversed and manipulated

    Example 1 Create a jQuery object using an XML string and obtain the value of the t it le node

    HTML

    ltp id=someElementgtltpgtltp id=anotherElementgtltpgt

    Javascript

    var xml = ltrss version=20gtltchannelgtlttitlegtRSS Titlelttitlegtltchannelgtltrssgt xmlDoc = $parseXML( xml ) $xml = $( xmlDoc ) $title = $xmlfind( title )

    append RSS Title to someElement $( someElement )append( $titletext() )

    change the title to XML Title $titletext( XML Title )

    append XML Title to anotherElement $( anotherElement )append( $titletext() )

    jQuerytype

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

    Added in version 143

    jQuerytype(obj)String

    objObject 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

    If the object is undef ined or null then undef ined or null is returned accordingly

    If the object has an internal [[Class]] equivalent to one of the browsers built -in objectsthe associated name is returned (More details about this technique)

    jQuerytype(true) === boolean

    jQuerytype(3) === number

    jQuerytype(test) === string

    jQuerytype(funct ion()) === funct ion

    jQuerytype([]) === array

    jQuerytype(new Date()) === date

    jQuerytype(test ) === regexp

    Everything else returns object as its type

    Example 1 Find out if the parameter is a RegExp

    Javascript

    $(b)append( + jQuerytype(test) )

    HTML

    Is it a RegExp ltbgtltbgt

    jQueryisWindow

    Determine whether the argument is a window

    Added in version 143

    jQueryisWindow(obj)boolean

    objObject Object to test whether or not it is a window

    This is used in a number of places in jQuery to determine if were operat ing against a browserwindow (such as the current window or an if rame)

    Example 1 Finds out if the parameter is a window

    Javascript

    $(b)append( + $isWindow(window) )

    HTML

    Is window a window ltbgtltbgt

    jQueryparseJSON

    Takes a well-formed JSON string and returns the result ing JavaScript object

    Added in version 141

    jQueryparseJSON(json)Object

    jsonString The JSON string to parse

    Passing in a malformed JSON string may result in an except ion being thrown For example thefollowing are all malformed JSON strings

    test 1 (test does not have double quotes around it )

    test 1 (test is using single quotes instead of double quotes)

    Addit ionally if you pass in nothing an empty string null or undef ined null will be returned fromparseJSON Where the browser provides a nat ive implementat ion of JSONparse jQuery uses itto parse the string For details on the JSON format see ht tpjsonorg

    Example 1 Parse a JSON string

    Javascript

    var obj = jQueryparseJSON(nameJohn)alert( objname === John )

    jQueryproxy see Events

    jQuerycontains

    Check to see if a DOM element is within another DOM element

    Added in version 14

    jQuerycontains(container contained)Boolean

    containerElement The DOM element that may contain the other element

    containedElement The DOM element that may be contained by the other element

    Example 1 Check if an element is inside another Text and comment nodes are not supported

    Javascript

    jQuerycontains(documentdocumentElement documentbody) truejQuerycontains(documentbody documentdocumentElement) false

    jQuerynoop

    An empty funct ion

    Added in version 14

    jQuerynoop()Funct ion

    You can use this empty funct ion when you wish to pass around a funct ion that will do nothing

    This is useful for plugin authors who of fer opt ional callbacks in the case that no callback isgiven something like jQuerynoop could execute

    jQueryglobalEval

    Execute some JavaScript code globally

    Added in version 104

    jQueryglobalEval(code)

    codeString The JavaScript code to execute

    This method behaves dif ferent ly f rom using a normal JavaScript eval() in that it s executedwithin the global context (which is important for loading external scripts dynamically)

    Example 1 Execute a script in the global context

    Javascript

    function test() jQueryglobalEval(var newVar = true)test() newVar === true

    jQueryisXMLDoc

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

    Added in version 114

    jQueryisXMLDoc(node)Boolean

    nodeElement The DOM node that will be checked to see if it s in an XML document

    Example 1 Check an object to see if it s in an XML document

    Javascript

    jQueryisXMLDoc(document) falsejQueryisXMLDoc(documentbody) false

    jQueryremoveData see Data

    jQuerydata see Data

    jQuerydata see Data

    jQuerydequeue see Data

    jQueryqueue see Data

    jQueryqueue see Data

    clearQueue see Data

    jQueryisEmptyObject

    Check to see if an object is empty (contains no propert ies)

    Added in version 14

    jQueryisEmptyObject(object)Boolean

    object Object The object that will be checked to see if it s empty

    As of jQuery 14 this method checks both propert ies on the object itself and propert iesinherited f rom prototypes (in that it doesnt use hasOwnProperty) The argument shouldalways be a plain JavaScript Object as other types of object (DOM elements primit ivestringsnumbers host objects) may not give consistent results across browsers To determine ifan object is a plain JavaScript object use $isPlainObject()

    Example 1 Check an object to see if it s empty

    Javascript

    jQueryisEmptyObject() truejQueryisEmptyObject( foo bar ) false

    jQueryisPlainObject

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

    Added in version 14

    jQueryisPlainObject(object)Boolean

    object Object The object that will be checked to see if it s a plain object

    Note Host objects (or objects used by browser host environments to complete the execut ionenvironment of ECMAScript) have a number of inconsistencies which are dif f icult to robust lyfeature detect cross-plat form As a result of this $isPlainObject() may evaluate inconsistent lyacross browsers in certain instances

    An example of this is a test against documentlocat ion using $isPlainObject() as follows

    consolelog($isPlainObject(documentlocation))

    which throws an invalid pointer except ion in IE8 With this in mind it s important to be aware ofany of the gotchas involved in using $isPlainObject() against older browsers Some basicexample of use-cases that do funct ion correct ly cross-browser can be found below

    Example 1 Check an object to see if it s a plain object

    Javascript

    jQueryisPlainObject() truejQueryisPlainObject(test) false

    dequeue see Data

    queue see Data

    queue see Data

    jQuerybrowser

    Contains f lags for the useragent read from navigatoruserAgent We recommend against usingthis property please try to use feature detect ion instead (see jQuerysupport) jQuerybrowsermay be moved to a plugin in a future release of jQuery

    Added in version 10

    The $browser property provides informat ion about the web browser that is accessing thepage as reported by the browser itself It contains f lags for each of the four most prevalentbrowser classes (Internet Explorer Mozilla Webkit and Opera) as well as version informat ion

    Available f lags are

    webkit (as of jQuery 14)

    safari (deprecated)

    opera

    msie

    mozilla

    This property is available immediately It is therefore safe to use it to determine whether or notto call $(document)ready() The $browser property is deprecated in jQuery 13 and itsfunct ionality may be moved to a team-supported plugin in a future release of jQuery

    Because $browser uses navigatoruserAgent to determine the plat form it is vulnerable tospoof ing by the user or misrepresentat ion by the browser itself It is always best to avoidbrowser-specif ic code ent irely where possible The $support property is available for detect ionof support for part icular features rather than relying on $browser

    Example 1 Show the browser info

    Javascript

    jQueryeach(jQuerybrowser function(i val) $(ltdivgt + i + ltspangt + val + ltspangt) appendTo( documentbody ) )

    CSS

    p colorgreen font-weightbolder margin3px 0 0 10px div colorblue margin-left20px font-size14px span colorred

    HTML

    ltpgtBrowser infoltpgt

    Example 2 Returns t rue if the current useragent is some version of Microsoft s InternetExplorer

    Javascript

    $browsermsie

    Example 3 Alerts this is WebKit only for WebKit browsers

    Javascript

    i f ($browserwebkit) alert( this is webkit )

    Example 4 Alerts Do stuf f for Firefox 3 only for Firefox 3 browsers

    Javascript

    var ua = $browser i f ( uamozil la ampamp uaversionsl ice(03) == 19 ) alert( Do stuff for firefox 3 )

    Example 5 Set a CSS property that s specif ic to a part icular browser

    Javascript

    i f ( $browsermsie ) $(div ul l i)css( display inl ine ) else $(div ul l i)css( display inl ine-table )

    jQuerybrowserversion

    The version number of the rendering engine for the users browser

    Added in version 113

    Here are some typical results

    Internet Explorer 60 70 80

    MozillaFirefoxFlockCamino 1712 1813 19

    Opera 1006 1101

    SafariWebkit 3128 4189

    Note that IE8 claims to be 7 in Compat ibility View

    Example 1 Returns the version number of the rendering engine used by the users currentbrowser For example FireFox 4 returns 20 (the version of the Gecko rendering engine itut ilizes)

    Javascript

    $(p)html( The version number of the rendering engine your browser uses is ltspangt + $browserversion + ltspangt )

    CSS

    p colorblue margin20px span colorred

    HTML

    ltpgtltpgt

    Example 2 Alerts the version of IEs rendering engine that is being used

    Javascript

    i f ( $browsermsie ) alert( $browserversion )

    Example 3 Often you only care about the major number the whole number which you canget by using JavaScript s built -in parseInt() funct ion

    Javascript

    i f ( $browsermsie ) alert( parseInt($browserversion 10) )

    jQuerytrim

    Remove the whitespace from the beginning and end of a string

    Added in version 10

    jQueryt rim(str)String

    strString The string to t rim

    The $t rim() funct ion removes all newlines spaces (including non-breaking spaces) and tabsfrom the beginning and end of the supplied string If these whitespace characters occur in themiddle of the string they are preserved

    Example 1 Remove the two white spaces at the start and at the end of the string

    Javascript

    $(button)cl ick(function () var str = lots of spaces before and after alert( + str + )

    str = jQuerytrim(str)alert( + str + - no longer))

    HTML

    ltbuttongtShow Trim Exampleltbuttongt

    Example 2 Remove the two white spaces at the start and at the end of the string

    Javascript

    $trim( hello how are you )

    Results

    hello how are you

    jQueryisFunction

    Determine if the argument passed is a Javascript funct ion object

    Added in version 12

    jQueryisFunct ion(obj)boolean

    objObject Object to test whether or not it is a funct ion

    Note As of jQuery 13 funct ions provided by the browser like alert() and DOM elementmethods like getAttribute() are not guaranteed to be detected as funct ions in browsers suchas Internet Explorer

    Example 1 Test a few parameter examples

    Javascript

    function stub() var objs = [ function () x15 y20 null stub function ]

    jQueryeach(objs function (i) var isFunc = jQueryisFunction(objs[i]) $(span)eq(i)text(isFunc) )

    CSS

    div colorblue margin2px font-size14px span colorred

    HTML

    ltdivgtjQueryisFunction(objs[0]) = ltspangtltspangtltdivgt

    ltdivgtjQueryisFunction(objs[1]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[2]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[3]) = ltspangtltspangtltdivgt

    ltdivgtjQueryisFunction(objs[4]) = ltspangtltspangtltdivgt

    Example 2 Finds out if the parameter is a funct ion

    Javascript

    $isFunction(function())

    Results

    true

    jQueryisArray

    Determine whether the argument is an array

    Added in version 13

    jQueryisArray(obj)boolean

    objObject Object to test whether or not it is an array

    $isArray() returns a Boolean indicat ing whether the object is a JavaScript array (not an array-like object such as a jQuery object)

    Example 1 Finds out if the parameter is an array

    Javascript

    $(b)append( + $isArray([]) )

    HTML

    Is [] an Array ltbgtltbgt

    jQueryunique

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

    Added in version 113

    jQueryunique(array)Array

    arrayArray The Array of DOM elements

    The $unique() funct ion searches through an array of objects sort ing the array and removingany duplicate nodes This funct ion only works on plain JavaScript arrays of DOM elements andis chief ly used internally by jQuery

    As of jQuery 14 the results will always be returned in document order

    Example 1 Removes any duplicate elements f rom the array of divs

    Javascript

    var divs = $(div)get() unique() must take a native array

    add 3 elements of class dup too (they are divs) divs = divsconcat($(dup)get()) $(diveq(1))text(Pre-unique there are + divslength + elements)

    divs = jQueryunique(divs) $(diveq(2))text(Post-unique there are + divslength + elements) css(color red)

    CSS

    div colorblue

    HTML

    ltdivgtThere are 6 divs in this documentltdivgt ltdivgtltdivgt ltdiv class=dupgtltdivgt ltdiv class=dupgtltdivgt

    ltdiv class=dupgtltdivgt ltdivgtltdivgt

    jQuerymerge

    Merge the contents of two arrays together into the f irst array

    Added in version 10

    jQuerymerge(f irst second)Array

    f irst Array The f irst array to merge the elements of second added

    secondArray The second array to merge into the f irst unaltered

    The $merge() operat ion forms an array that contains all elements f rom the two arrays Theorders of items in the arrays are preserved with items from the second array appended The$merge() funct ion is destruct ive It alters the f irst parameter to add the items from the second

    If you need the original f irst array make a copy of it before calling $merge() Fortunately$merge() itself can be used for this duplicat ion

    var newArray = $merge([] oldArray)

    This shortcut creates a new empty array and merges the contents of oldArray into it ef fect ively cloning the array

    Prior to jQuery 14 the arguments should be true Javascript Array objects use $makeArray ifthey are not

    Example 1 Merges two arrays altering the f irst argument

    Javascript

    $merge( [012] [234] )

    Results

    [012234]

    Example 2 Merges two arrays altering the f irst argument

    Javascript

    $merge( [321] [432] )

    Results

    [321432]

    Example 3 Merges two arrays but uses a copy so the original isnt altered

    Javascript

    var first = [abc]var second = [de f]$merge( $merge([]first) second)

    Results

    [abcdef]

    jQueryinArray

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

    Added in version 12

    jQueryinArray(value array)Number

    valueAny The value to search for

    arrayArray An array through which to search

    The $inArray() method is similar to JavaScript s nat ive indexOf() method in that it returns -1when it doesnt f ind a match If the f irst element within the array matches value $inArray()returns 0

    Because JavaScript t reats 0 as loosely equal to false (ie 0 == false but 0 == false) if werechecking for the presence of value within array we need to check if it s not equal to (or greaterthan) -1

    Example 1 Report the index of some elements in the array

    Javascript

    var arr = [ 4 Pete 8 John ]

    $(spaneq(0))text(jQueryinArray(John arr))$(spaneq(1))text(jQueryinArray(4 arr))$(spaneq(2))text(jQueryinArray(Karl arr))

    CSS

    div colorblue span colorred

    HTML

    ltdivgtJohn found at ltspangtltspangtltdivgtltdivgt4 found at ltspangtltspangtltdivgtltdivgtKarl not found so ltspangtltspangtltdivgt

    jQuerymap

    Translate all items in an array or object to new array of items

    Added in version 16

    jQuerymap(arrayOrObject callback( value indexOrKey ))Array

    arrayOrObject ArrayObject The Array or Object to t ranslate

    callback( value indexOrKey)Funct ion

    The funct ion to process each item against The f irstargument to the funct ion is the value the secondargument is the index or key of the array or objectproperty The funct ion can return any value to add to thearray A returned array will be f lat tened into the result ingarray Within the funct ion this refers to the global (window)object

    The $map() method applies a funct ion to each item in an array or object and maps the resultsinto a new array Prior to jQuery 16 $map() supports t raversing arrays only As of jQuery 16 italso t raverses objects

    Array-like objects acirceurordquo those with a length property and a value on the length - 1 index acirceurordquo mustbe converted to actual arrays before being passed to $map() The jQuery library provides$makeArray() for such conversions

    The following object masquerades as an arrayvar fakeArray = length 1 0 Addy 1 Subtracty

    Therefore convert it to a real arrayvar realArray = $makeArray( fakeArray )

    Now it can be used reliably with $map()$map( realArray function(val i) do something )

    The translat ion funct ion that is provided to this method is called for each top-level element inthe array or object and is passed two arguments The element s value and its index or keywithin the array or object

    The funct ion can return

    the translated value which will be mapped to the result ing array

    null to remove the item

    an array of values which will be f lat tened into the full array

    Example 1 A couple examples of using map()

    Javascript

    var arr = [ a b c d e ] $(div)text(arrjoin( ))

    arr = jQuerymap(arr function(n i) return (ntoUpperCase() + i) ) $(p)text(arrjoin( ))

    arr = jQuerymap(arr function (a) return a + a ) $(span)text(arrjoin( ))

    CSS

    div colorblue p colorgreen margin0 span colorred

    HTML

    ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

    Example 2 Map the original array to a new one and add 4 to each value

    Javascript

    $map( [012] function(n) return n + 4 )

    Results

    [4 5 6]

    Example 3 Maps the original array to a new one and adds 1 to each value if it is bigger thenzero otherwise it s removed

    Javascript

    $map( [012] function(n) return n gt 0 n + 1 null )

    Results

    [2 3]

    Example 4 Map the original array to a new one each element is added with its original valueand the value plus one

    Javascript

    $map( [012] function(n) return [ n n + 1 ] )

    Results

    [0 1 1 2 2 3]

    Example 5 Map the original object to a new array and double each value

    Javascript

    var dimensions = width 10 height 15 length 20 dimensions = $map( dimensions function( value index ) return value 2)

    Results

    [20 30 40]

    Example 6 Map an object s keys to an array

    Javascript

    var dimensions = width 10 height 15 length 20 keys = $map( dimensions function( value index ) return index )

    Results

    [width height length]

    Example 7 Maps the original array to a new one each element is squared

    Javascript

    $map( [0123] function (a) return a a )

    Results

    [0 1 4 9]

    Example 8 Remove items by returning null f rom the funct ion This removes any numbers lessthan 50 and the rest are decreased by 45

    Javascript

    $map( [0 1 52 97] function (a) return (a gt 50 a - 45 null) )

    Results

    [7 52]

    Example 9 Augment ing the result ing array by returning an array inside the funct ion

    Javascript

    var array = [0 1 52 97]array = $map(array function(a index) return [a - 45 index])

    Results

    [-45 0 -44 1 7 2 52 3]

    jQuerymakeArray

    Convert an array-like object into a t rue JavaScript array

    Added in version 12

    jQuerymakeArray(obj)Array

    objObject Any object to turn into a nat ive Array

    Many methods both in jQuery and in JavaScript in general return objects that are array-like Forexample the jQuery factory funct ion $() returns a jQuery object that has many of thepropert ies of an array (a length the [] array access operator etc) but is not exact ly the sameas an array and lacks some of an arrays built -in methods (such as pop() and reverse())

    Note that af ter the conversion any special features the object had (such as the jQuerymethods in our example) will no longer be present The object is now a plain array

    Example 1 Turn a collect ion of HTMLElements into an Array of them

    Javascript

    var elems = documentgetElementsByTagName(div) returns a nodeList var arr = jQuerymakeArray(elems) arrreverse() use an Array method on l ist of dom elements $(arr)appendTo(documentbody)

    CSS

    div colorred

    HTML

    ltdivgtFirstltdivgt ltdivgtSecondltdivgt ltdivgtThirdltdivgt

    ltdivgtFourthltdivgt

    Example 2 Turn a jQuery object into an array

    Javascript

    var obj = $( l i ) var arr = $makeArray(obj)

    Results

    (typeof obj === object ampamp objjquery) === truejQueryisArray(arr) === true

    jQuerygrep

    Finds the elements of an array which sat isfy a f ilter funct ion The original array is not af fected

    Added in version 10

    jQuerygrep(array funct ion(elementOfArray indexInArray) invert)Array

    arrayArray The array to search through

    funct ion(elementOfArrayindexInArray)Funct ion

    The funct ion to process each item against The f irstargument to the funct ion is the item and the secondargument is the index The funct ion should return a Booleanvalue this will be the global window object

    invert Boolean (opt ional) If invert is false or not provided then thefunct ion returns an array consist ing of all elements for whichcallback returns t rue If invert is t rue then the funct ionreturns an array consist ing of all elements for whichcallback returns false

    The $grep() method removes items from an array as necessary so that all remaining items passa provided test The test is a funct ion that is passed an array item and the index of the itemwithin the array Only if the test returns t rue will the item be in the result array

    The f ilter funct ion will be passed two arguments the current array item and its index The f ilterfunct ion must return t rue to include the item in the result array

    Example 1 Filters the original array of numbers leaving that are not 5 and have an index greaterthan 4 Then it removes all 9s

    Javascript

    var arr = [ 1 9 3 8 6 1 5 9 4 7 3 8 6 9 1 ]$(div)text(arrjoin( ))

    arr = jQuerygrep(arr function(n i) return (n = 5 ampamp i gt 4))$(p)text(arrjoin( ))

    arr = jQuerygrep(arr function (a) return a = 9 )$(span)text(arrjoin( ))

    CSS

    div colorblue p colorgreen margin0 span colorred

    HTML

    ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

    Example 2 Filter an array of numbers to include only numbers bigger then zero

    Javascript

    $grep( [012] function(ni) return n gt 0 )

    Results

    [1 2]

    Example 3 Filter an array of numbers to include numbers that are not bigger than zero

    Javascript

    $grep( [012] function(ni) return n gt 0true)

    Results

    [0]

    jQueryextend

    Merge the contents of two or more objects together into the f irst object

    Added in version 114

    jQueryextend(deep target object1 objectN)Object

    deepBoolean (opt ional) If t rue the merge becomes recursive (aka deep copy)

    targetObject The object to extend It will receive the new propert ies

    object1Object An object containing addit ional propert ies to merge in

    objectNObject (opt ional) Addit ional objects containing propert ies to merge in

    When we supply two or more objects to $extend() propert ies f rom all of the objects are addedto the target object

    If only one argument is supplied to $extend() this means the target argument was omit ted Inthis case the jQuery object itself is assumed to be the target By doing this we can add newfunct ions to the jQuery namespace This can be useful for plugin authors wishing to add newmethods to JQuery

    Keep in mind that the target object (f irst argument) will be modif ied and will also be returnedfrom $extend() If however we want to preserve both of the original objects we can do so bypassing an empty object as the target

    var object = $extend( object1 object2)

    The merge performed by $extend() is not recursive by default if a property of the f irst object isitself an object or array it will be completely overwrit ten by a property with the same key in thesecond object The values are not merged This can be seen in the example below by examiningthe value of banana However by passing true for the f irst funct ion argument objects will berecursively merged

    Undef ined propert ies are not copied However propert ies inherited f rom the object s prototypewill be copied over For performance reasons propert ies that have values of built -in JavaScripttypes such as Date or RegExp are not re-constructed and will appear as plain Objects in theresult ing object or array

    Note When performing a deep extend Object and Array are extended howeverprimitive types such string boolean and number are not For specific needs thatfall outside of this behaviour it is recommended to write a custom extend methodas this will be significantly faster from a performance perspective

    Example 1 Merge two objects modifying the f irst

    Javascript

    var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

    merge object2 into object1 $extend(object1 object2)

    var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

    $(log)append( printObj(object1) )

    HTML

    ltdiv id=loggtltdivgt

    Example 2 Merge two objects recursively modifying the f irst

    Javascript

    var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

    merge object2 into object1 recursively $extend(true object1 object2)

    var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

    $(log)append( printObj(object1) )

    HTML

    ltdiv id=loggtltdivgt

    Example 3 Merge defaults and opt ions without modifying the defaults This is a commonplugin development pattern

    Javascript

    var defaults = validate false l imit 5 name foo var options = validate true name bar

    merge defaults and options without modifying defaults var settings = $extend( defaults options)

    var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

    $(log)append( ltdivgtltbgtsettings -- ltbgt + printObj(settings) + ltdivgt )$(log)append( ltdivgtltbgtoptions -- ltbgt + printObj(options) + ltdivgt )

    HTML

    ltdiv id=loggtltdivgt

    jQueryeach

    A generic iterator funct ion which can be used to seamlessly iterate over both objects andarrays Arrays and array-like objects with a length property (such as a funct ions argumentsobject) are iterated by numeric index f rom 0 to length-1 Other objects are iterated via theirnamed propert ies

    Added in version 10

    jQueryeach(collect ion callback(indexInArray valueOfElement))Object

    collect ionObject The object or array to iterate over

    callback(indexInArrayvalueOfElement)Funct ion

    The funct ion that will be executed on everyobject

    The $each() funct ion is not the same as $(selector)each() which is used to iterate exclusivelyover a jQuery object The $each() funct ion can be used to iterate over any collect ion whetherit is a map (JavaScript object) or an array In the case of an array the callback is passed an arrayindex and a corresponding array value each t ime (The value can also be accessed through the

    this keyword but Javascript will always wrap the this value as an Object even if it is a simplestring or number value) The method returns its f irst argument the object that was iterated

    $each([52 97] function(index value) alert(index + + value) )

    This produces two messages

    0 52

    1 97

    If a map is used as the collect ion the callback is passed a key-value pair each t ime

    var map = flammable inflammable duh no duh $each(map function(key value) alert(key + + value) )

    Once again this produces two messages

    f lammable inf lammable

    duh no duh

    We can break the $each() loop at a part icular iterat ion by making the callback funct ion returnfalse Returning non-false is the same as a cont inue statement in a for loop it will skipimmediately to the next iterat ion

    Example 1 Iterates through the array displaying each number as both a word and numeral

    Javascript

    var arr = [ one two three four five ] var obj = one1 two2 three3 four4 five5

    jQueryeach(arr function() $( + this)text(Mine is + this + ) return (this = three) wil l stop running after three )

    jQueryeach(obj function(i val) $( + i)append(documentcreateTextNode( - + val)) )

    CSS

    div colorblue divfive colorred

    HTML

    ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt ltdiv id=fourgtltdivgt ltdiv id=fivegtltdivgt

    Example 2 Iterates over items in an array accessing both the current item and its index

    Javascript

    $each( [abc] function(i l) alert( Index + i + + l ) )

    Example 3 Iterates over the propert ies in an object accessing both the current item and its key

    Javascript

    $each( name John lang JS function(k v) alert( Key + k + Value + v ) )

    jQueryboxModel

    Deprecated in jQuery 13 (see jQuerysupport) States if the current page in the users browseris being rendered using the W3C CSS Box Model

    Added in version 10

    Example 1 Returns the box model for the if rame

    Javascript

    $(p)html(The box model for this iframe is ltspangt + jQueryboxModel + ltspangt)

    CSS

    p colorblue margin20px span colorred

    HTML

    ltpgt ltpgt

    Example 2 Returns false if the page is in Quirks Mode in Internet Explorer

    Javascript

    $boxModel

    Results

    false

    jQuerysupport

    A collect ion of propert ies that represent the presence of dif ferent browser features or bugs

    Added in version 13

    Rather than using $browser to detect the current user agent and alter the page presentat ionbased on which browser is running it is a good pract ice to perform feature detect ion Thismeans that prior to execut ing code which relies on a browser feature we test to ensure thatthe feature works properly To make this process simpler jQuery performs many such tests andmakes the results available to us as propert ies of the jQuerysupport object

    The values of all the support propert ies are determined using feature detect ion (and do notuse any form of browser snif f ing)

    Following are a few resources that explain how feature detection works

    httppetermichauxcaarticlesfeature-detection-state-of-the-art-browser-scripting

    httpwwwjibberingcomfaqfaq_notesnot_browser_detecthtml

    httpyurathinkweb2comcft

    While jQuery includes a number of propert ies developers should feel f ree to add their own as

    While jQuery includes a number of propert ies developers should feel f ree to add their own astheir needs dictate Many of the jQuerysupport propert ies are rather low-level so they aremost useful for plugin and jQuery core development rather than general day-to-daydevelopment Since jQuery requires these tests internally they must be performed on everypage load for that reason this list is kept short and limited to features needed by jQuery itself

    The tests included in jQuerysupport are as follows

    ajax is equal to t rue if a browser is able to create an XMLHttpRequest object

    boxModel is equal to t rue if the page is rendering according to the W3C CSS Box Model(is current ly false in IE 6 and 7 when they are in Quirks Mode) This property is null unt ildocument ready occurs

    changeBubbles is equal to t rue if the change event bubbles up the DOM tree asrequired by the W3C DOM event model (It is current ly false in IE and jQuery simulatesbubbling)

    checkClone is equal to t rue if a browser correct ly clones the checked state of radiobuttons or checkboxes in document f ragments

    checkOn is equal to t rue if the value of a checkbox defaults to on when no value isspecif ied

    cors is equal to t rue if a browser can create an XMLHttpRequest object and if thatXMLHttpRequest object has a withCredent ials property To enable cross-domainrequests in environments that do not support cors yet but do allow cross-domain XHRrequests (windows gadget etc) set $support cors = t rue CORS WD

    cssFloat is equal to t rue if the name of the property containing the CSS f loat value iscssFloat as def ined in the CSS Spec (It is current ly false in IE it uses styleFloat instead)

    hrefNormalized is equal to t rue if the getAttribute() method retrieves the href at t ributeof elements unchanged rather than normalizing it to a fully-qualif ied URL (It is current lyfalse in IE the URLs are normalized)

    htmlSerialize is equal to t rue if the browser is able to serializeinsert ltlinkgt elementsusing the innerHTML property of elements (is current ly false in IE)

    leadingWhitespace is equal to t rue if the browser inserts content with innerHTMLexact ly as providedacirceurordquospecif ically if leading whitespace characters are preserved (It iscurrent ly false in IE 6-8)

    noCloneChecked is equal to t rue if cloned DOM elements copy over the state of thechecked expando (It is current ly false in IE) (Added in jQuery 151)

    noCloneEvent is equal to t rue if cloned DOM elements are created without eventhandlers (that is if the event handlers on the source element are not cloned) (It iscurrent ly false in IE)

    opacity is equal to t rue if a browser can properly interpret the opacity style property (Itis current ly false in IE it uses alpha f ilters instead)

    optDisabled is equal to t rue if opt ion elements within disabled select elements are notautomat ically marked as disabled

    optSelected is equal to t rue if an ltopt iongt element that is selected by default has aworking selected property

    scriptEval() is equal to t rue if inline scripts are automat ically evaluated and executedwhen inserted into the document using standard DOM manipulat ion methods such asappendChild() and createTextNode() (It is current ly false in IE it uses text to insertexecutable scripts)

    Note No longer supported removed in jQuery 16 Prior to jQuery 151 the scriptEval()method was the stat ic scriptEval property The change to a method allowed the test tobe deferred unt il f irst use to prevent content security policy inline-script violat ions

    style is equal to t rue if inline styles for an element can be accessed through the DOMattribute called style as required by the DOM Level 2 specif icat ion In this casegetAttribute(style) can retrieve this value in Internet Explorer cssText is used for thispurpose

    submitBubbles is equal to t rue if the submit event bubbles up the DOM tree as requiredby the W3C DOM event model (It is current ly false in IE and jQuery simulates bubbling)

    tbody is equal to t rue if an empty lttablegt element can exist without a lttbodygt elementAccording to the HTML specif icat ion this sub-element is opt ional so the property shouldbe true in a fully-compliant browser If false we must account for the possibility of thebrowser inject ing lttbodygt tags implicit ly (It is current ly false in IE which automat icallyinserts tbody if it is not present in a string assigned to innerHTML)

    Example 1 Returns the box model for the if rame

    Javascript

    $(p)html(This frame uses the W3C box model ltspangt + jQuerysupportboxModel + ltspangt)

    CSS

    p colorblue margin20px span colorred

    HTML

    ltpgt ltpgt

    Example 2 Returns false if the page is in QuirksMode in Internet Explorer

    Javascript

    jQuerysupportboxModel

    Results

    false

    Plugin Authoring

    • JQuery Documentation
      • Core
        • jQueryholdReady
        • jQuerywhen
        • jQuerysub
        • jQuerynoConflict
        • jQuery
          • Selector Context
          • Using DOM elements
          • Cloning jQuery Objects
          • Returning an Empty Set
            • jQuery
              • Creating New Elements
                • jQuery
                  • Selectors
                    • focus $(focus)
                    • selected $(selected)
                    • checked $(checked)
                    • disabled $(disabled)
                    • enabled $(enabled)
                    • file $(file)
                    • button $(button)
                    • reset $(reset)
                    • image $(image)
                    • submit $(submit)
                    • checkbox $(checkbox)
                    • radio $(radio)
                    • password $(password)
                    • text $(text)
                    • input $(input)
                    • only-child $(only-child)
                    • last-child $(last-child)
                    • first-child $(first-child)
                    • nth-child $(nth-child(indexevenoddequation))
                    • attributeContainsPrefix $([attribute|=value])
                    • attributeContainsWord $([attribute~=value])
                    • attributeMultiple $([attributeFilter1][attributeFilter2][attributeFilterN])
                    • attributeContains $([attribute=value])
                    • attributeEndsWith $([attribute$=value])
                    • attributeStartsWith $([attribute^=value])
                    • attributeNotEqual $([attribute=value])
                    • attributeEquals $([attribute=value])
                    • attributeHas $([attribute])
                    • visible $(visible)
                    • hidden $(hidden)
                    • parent $(parent)
                    • has $(has(selector))
                    • empty $(empty)
                    • contains $(contains(text))
                    • animated $(animated)
                    • header $(header)
                    • lt $(lt(index))
                    • gt $(gt(index))
                    • eq $(eq(index))
                    • odd $(odd)
                    • even $(even)
                    • not $(not(selector))
                    • Additional Notes
                    • last $(last)
                    • first $(first)
                    • next siblings $(prev ~ siblings)
                    • next adjacent $(prev + next)
                    • child $(parent gt child)
                    • descendant $(ancestor descendant)
                    • multiple $(selector1 selector2 selectorN)
                    • all $()
                    • class $(class)
                    • element $(element)
                    • id $(id)
                      • Traversing
                        • has
                        • parentsUntil
                        • prevUntil
                        • nextUntil
                        • each
                        • first
                        • last
                        • slice
                          • Negative Indices
                            • end
                            • andSelf
                            • siblings
                            • prevAll
                            • prev
                            • parents
                            • parent
                            • offsetParent
                            • nextAll
                            • next
                            • find
                            • contents
                            • closest
                            • closest
                            • children
                            • add
                            • not
                              • Removing Specific Elements
                                • map
                                • is
                                  • Using a Function
                                    • eq
                                    • filter
                                      • Using a Filter Function
                                          • Attributes
                                            • removeProp
                                            • prop
                                            • prop
                                              • Computed property values
                                                • val
                                                • val
                                                • html
                                                • html
                                                • toggleClass
                                                • removeClass
                                                • hasClass
                                                • removeAttr
                                                • attr
                                                • attr
                                                  • Setting a simple attribute
                                                  • Setting several attributes at once
                                                  • Computed attribute values
                                                    • addClass
                                                      • CSS
                                                        • jQuerycssHooks
                                                          • Feature Testing
                                                          • Defining a complete cssHook
                                                          • Special units
                                                          • Animating with cssHooks
                                                            • outerWidth
                                                            • outerHeight
                                                            • innerWidth
                                                            • innerHeight
                                                            • width
                                                            • width
                                                            • height
                                                            • height
                                                            • scrollLeft
                                                            • scrollLeft
                                                            • scrollTop
                                                            • scrollTop
                                                            • position
                                                            • offset
                                                            • offset
                                                            • css
                                                            • css
                                                            • toggleClass see Attributes
                                                            • removeClass see Attributes
                                                            • hasClass see Attributes
                                                            • addClass see Attributes
                                                              • Manipulation
                                                                • removeProp see Attributes
                                                                • prop see Attributes
                                                                • prop see Attributes
                                                                • outerWidth see CSS
                                                                • outerHeight see CSS
                                                                • innerWidth see CSS
                                                                • innerHeight see CSS
                                                                • width see CSS
                                                                • width see CSS
                                                                • height see CSS
                                                                • height see CSS
                                                                • scrollLeft see CSS
                                                                • scrollLeft see CSS
                                                                • scrollTop see CSS
                                                                • scrollTop see CSS
                                                                • position see CSS
                                                                • offset see CSS
                                                                • offset see CSS
                                                                • css see CSS
                                                                • css see CSS
                                                                • unwrap
                                                                • detach
                                                                • clone
                                                                • remove
                                                                • empty
                                                                • replaceAll
                                                                • replaceWith
                                                                • wrapInner
                                                                • wrapAll
                                                                • wrap
                                                                • insertBefore
                                                                • before
                                                                  • Additional Arguments
                                                                    • insertAfter
                                                                    • after
                                                                      • Inserting Disconnected DOM nodes
                                                                      • Passing a Function
                                                                      • Additional Arguments
                                                                        • prependTo
                                                                        • prepend
                                                                          • Additional Arguments
                                                                            • appendTo
                                                                            • append
                                                                              • Additional Arguments
                                                                                • val see Attributes
                                                                                • val see Attributes
                                                                                • text
                                                                                • text
                                                                                • html see Attributes
                                                                                • html see Attributes
                                                                                • toggleClass see Attributes
                                                                                • removeClass see Attributes
                                                                                • hasClass see Attributes
                                                                                • removeAttr see Attributes
                                                                                • attr see Attributes
                                                                                • attr see Attributes
                                                                                • addClass see Attributes
                                                                                  • Data
                                                                                    • jQueryhasData
                                                                                    • jQueryremoveData
                                                                                    • jQuerydata
                                                                                    • jQuerydata
                                                                                    • jQuerydequeue
                                                                                    • jQueryqueue
                                                                                    • jQueryqueue
                                                                                    • clearQueue
                                                                                    • removeData
                                                                                    • data
                                                                                    • data
                                                                                    • dequeue
                                                                                    • queue
                                                                                    • queue
                                                                                      • Forms
                                                                                        • submit
                                                                                        • select
                                                                                        • change
                                                                                        • blur
                                                                                        • focus
                                                                                        • serializeArray
                                                                                        • serialize
                                                                                        • jQueryparam
                                                                                        • val see Attributes
                                                                                        • val see Attributes
                                                                                          • Events
                                                                                            • toggle
                                                                                            • eventnamespace
                                                                                            • undelegate
                                                                                            • delegate
                                                                                            • jQueryproxy
                                                                                            • focusout
                                                                                            • focusin
                                                                                            • eventisImmediatePropagationStopped
                                                                                            • eventstopImmediatePropagation
                                                                                            • eventisPropagationStopped
                                                                                            • eventstopPropagation
                                                                                            • eventisDefaultPrevented
                                                                                            • eventpreventDefault
                                                                                            • eventtimeStamp
                                                                                            • eventresult
                                                                                            • eventwhich
                                                                                            • eventpageY
                                                                                            • eventpageX
                                                                                            • eventcurrentTarget
                                                                                            • eventrelatedTarget
                                                                                            • eventdata
                                                                                            • eventtarget
                                                                                            • eventtype
                                                                                            • keydown
                                                                                            • scroll
                                                                                            • resize
                                                                                            • keyup
                                                                                            • keypress
                                                                                            • submit see Forms
                                                                                            • select see Forms
                                                                                            • change see Forms
                                                                                            • blur see Forms
                                                                                            • focus see Forms
                                                                                            • mousemove
                                                                                            • hover
                                                                                            • hover
                                                                                            • mouseleave
                                                                                            • mouseenter
                                                                                            • mouseout
                                                                                            • mouseover
                                                                                            • dblclick
                                                                                            • click
                                                                                            • mouseup
                                                                                            • mousedown
                                                                                            • error
                                                                                            • unload
                                                                                            • load
                                                                                            • ready
                                                                                              • Aliasing the jQuery Namespace
                                                                                                • die
                                                                                                • die
                                                                                                • live
                                                                                                  • Event Delegation
                                                                                                  • Multiple Events
                                                                                                  • Event Data
                                                                                                  • Event Context
                                                                                                  • Caveats
                                                                                                    • triggerHandler
                                                                                                    • trigger
                                                                                                    • one
                                                                                                    • unbind
                                                                                                      • Using Namespaces
                                                                                                      • Using the Event Object
                                                                                                        • bind
                                                                                                          • Multiple Events
                                                                                                          • Event Handlers
                                                                                                          • The Event object
                                                                                                          • Passing Event Data
                                                                                                              • Deferred Object
                                                                                                                • deferredpipe
                                                                                                                • deferredalways
                                                                                                                • promise
                                                                                                                • deferredpromise
                                                                                                                • jQuerywhen see Core
                                                                                                                • deferredresolveWith
                                                                                                                • deferredrejectWith
                                                                                                                • deferredfail
                                                                                                                • deferreddone
                                                                                                                • deferredthen
                                                                                                                • deferredreject
                                                                                                                • deferredisRejected
                                                                                                                • deferredisResolved
                                                                                                                • deferredresolve
                                                                                                                  • Effects
                                                                                                                    • fadeToggle
                                                                                                                      • Easing
                                                                                                                      • Callback Function
                                                                                                                        • jQueryfxinterval
                                                                                                                        • delay
                                                                                                                        • jQueryfxoff
                                                                                                                        • clearQueue see Data
                                                                                                                        • dequeue see Data
                                                                                                                        • queue see Data
                                                                                                                        • queue see Data
                                                                                                                        • stop
                                                                                                                        • animate
                                                                                                                          • Animation Properties and Values
                                                                                                                          • Duration
                                                                                                                          • Complete Function
                                                                                                                          • Basic Usage
                                                                                                                          • Step Function
                                                                                                                          • Easing
                                                                                                                          • Per-property Easing
                                                                                                                            • fadeTo
                                                                                                                            • fadeOut
                                                                                                                              • Easing
                                                                                                                              • Callback Function
                                                                                                                                • fadeIn
                                                                                                                                  • Easing
                                                                                                                                  • Callback Function
                                                                                                                                    • slideToggle
                                                                                                                                      • Easing
                                                                                                                                      • Callback Function
                                                                                                                                        • slideUp
                                                                                                                                          • Easing
                                                                                                                                          • Callback Function
                                                                                                                                            • slideDown
                                                                                                                                              • Easing
                                                                                                                                              • Callback Function
                                                                                                                                                • toggle
                                                                                                                                                • hide
                                                                                                                                                • show
                                                                                                                                                  • Ajax
                                                                                                                                                    • jQueryajaxPrefilter
                                                                                                                                                    • ajaxComplete
                                                                                                                                                    • serializeArray see Forms
                                                                                                                                                    • serialize see Forms
                                                                                                                                                    • jQueryajaxSetup
                                                                                                                                                    • ajaxSuccess
                                                                                                                                                    • ajaxStop
                                                                                                                                                    • ajaxStart
                                                                                                                                                    • ajaxSend
                                                                                                                                                    • ajaxError
                                                                                                                                                    • jQuerypost
                                                                                                                                                      • The jqXHR Object
                                                                                                                                                        • jQuerygetScript
                                                                                                                                                        • jQuerygetJSON
                                                                                                                                                          • JSONP
                                                                                                                                                          • The jqXHR Object
                                                                                                                                                            • jQueryget
                                                                                                                                                              • The jqXHR Object
                                                                                                                                                                • load
                                                                                                                                                                  • Loading Page Fragments
                                                                                                                                                                    • jQueryajax
                                                                                                                                                                      • The jqXHR Object
                                                                                                                                                                      • Callback Function Queues
                                                                                                                                                                      • Data Types
                                                                                                                                                                      • Sending Data to the Server
                                                                                                                                                                      • Advanced Options
                                                                                                                                                                      • Extending Ajax
                                                                                                                                                                        • jQueryparam see Forms
                                                                                                                                                                          • Miscellaneous
                                                                                                                                                                            • each see Traversing
                                                                                                                                                                            • toArray
                                                                                                                                                                            • index
                                                                                                                                                                              • Return Values
                                                                                                                                                                              • Detail
                                                                                                                                                                                • removeData see Data
                                                                                                                                                                                • data see Data
                                                                                                                                                                                • data see Data
                                                                                                                                                                                • get
                                                                                                                                                                                • size
                                                                                                                                                                                • jQuerynoConflict see Core
                                                                                                                                                                                • jQueryparam see Forms
                                                                                                                                                                                  • Dimensions
                                                                                                                                                                                    • outerWidth see CSS
                                                                                                                                                                                    • outerHeight see CSS
                                                                                                                                                                                    • innerWidth see CSS
                                                                                                                                                                                    • innerHeight see CSS
                                                                                                                                                                                    • width see CSS
                                                                                                                                                                                    • width see CSS
                                                                                                                                                                                    • height see CSS
                                                                                                                                                                                    • height see CSS
                                                                                                                                                                                      • Offset
                                                                                                                                                                                        • offsetParent see Traversing
                                                                                                                                                                                        • scrollLeft see CSS
                                                                                                                                                                                        • scrollLeft see CSS
                                                                                                                                                                                        • scrollTop see CSS
                                                                                                                                                                                        • scrollTop see CSS
                                                                                                                                                                                        • position see CSS
                                                                                                                                                                                        • offset see CSS
                                                                                                                                                                                        • offset see CSS
                                                                                                                                                                                          • Utilities
                                                                                                                                                                                            • jQuerynow
                                                                                                                                                                                            • jQueryparseXML
                                                                                                                                                                                            • jQuerytype
                                                                                                                                                                                            • jQueryisWindow
                                                                                                                                                                                            • jQueryparseJSON
                                                                                                                                                                                            • jQueryproxy see Events
                                                                                                                                                                                            • jQuerycontains
                                                                                                                                                                                            • jQuerynoop
                                                                                                                                                                                            • jQueryglobalEval
                                                                                                                                                                                            • jQueryisXMLDoc
                                                                                                                                                                                            • jQueryremoveData see Data
                                                                                                                                                                                            • jQuerydata see Data
                                                                                                                                                                                            • jQuerydata see Data
                                                                                                                                                                                            • jQuerydequeue see Data
                                                                                                                                                                                            • jQueryqueue see Data
                                                                                                                                                                                            • jQueryqueue see Data
                                                                                                                                                                                            • clearQueue see Data
                                                                                                                                                                                            • jQueryisEmptyObject
                                                                                                                                                                                            • jQueryisPlainObject
                                                                                                                                                                                            • dequeue see Data
                                                                                                                                                                                            • queue see Data
                                                                                                                                                                                            • queue see Data
                                                                                                                                                                                            • jQuerybrowser
                                                                                                                                                                                            • jQuerybrowserversion
                                                                                                                                                                                            • jQuerytrim
                                                                                                                                                                                            • jQueryisFunction
                                                                                                                                                                                            • jQueryisArray
                                                                                                                                                                                            • jQueryunique
                                                                                                                                                                                            • jQuerymerge
                                                                                                                                                                                            • jQueryinArray
                                                                                                                                                                                            • jQuerymap
                                                                                                                                                                                            • jQuerymakeArray
                                                                                                                                                                                            • jQuerygrep
                                                                                                                                                                                            • jQueryextend
                                                                                                                                                                                            • jQueryeach
                                                                                                                                                                                            • jQueryboxModel
                                                                                                                                                                                            • jQuerysupport
                                                                                                                                                                                              • Plugin Authoring

      $when($ajax(page1php) $ajax(page2php))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 ] i f ( Whip Ittest(jqXHRresponseText) ) alert(First page has Whip It somewhere) )

      Example 2 Execute the funct ion myFunc when both ajax requests are successful or myFailureif either one has an error

      Javascript

      $when($ajax(page1php) $ajax(page2php)) then(myFunc myFailure)

      jQuerysub

      Creates a new copy of jQuery whose propert ies and methods can be modif ied withoutaf fect ing the original jQuery object

      Added in version 15

      jQuerysub()jQuery

      There are two specif ic use cases for which jQuerysub() was created The f irst was for providinga painless way of overriding jQuery methods without completely destroying the originalmethods and another was for helping to do encapsulat ion and basic namespacing for jQueryplugins

      Note that jQuerysub() doesnt at tempt to do any sort of isolat ion - that s not its intent ion Allthe methods on the subd version of jQuery will st ill point to the original jQuery (events boundand triggered will st ill be through the main jQuery data will be bound to elements through themain jQuery Ajax queries and events will run through the main jQuery etc)

      Note that if youre looking to use this for plugin development you should f irst strongly considerusing something like the jQuery UI widget factory which manages both state and plugin sub-methods Some examples of using the jQuery UI widget factory to build a plugin

      The part icular use cases of this method can be best described through some examples

      Example 1 Adding a method to a jQuery sub so that it isnt exposed externally

      Javascript

      (function() var sub$ = jQuerysub()

      sub$fnmyCustomMethod = function() return just for me

      sub$(document)ready(function() sub$(body)myCustomMethod() just for me ) )() typeof jQuery(body)myCustomMethod undefined

      Example 2 Override some jQuery methods to provide new funct ionality

      Javascript

      (function() var myjQuery = jQuerysub()

      myjQueryfnremove = function() New functionality Trigger a remove event thistrigger(remove)

      Be sure to call the original jQuery remove method return jQueryfnremoveapply( this arguments )

      myjQuery(function($) $(menu)cl ick(function() $(this)find(submenu)remove() )

      A new remove event is now triggered from this copy of jQuery $(document)bind(remove function(e) $(etarget)parent()hide() ) ))()

      Regular jQuery doesnt trigger a remove event when removing an element This functionality is only contained within the modified myjQuery

      Example 3 Create a plugin that returns plugin-specif ic methods

      Javascript

      (function() Create a new copy of jQuery using sub() var plugin = jQuerysub()

      Extend that copy with the new plugin methods pluginfnextend( open function() return thisshow() close function() return thishide() )

      Add our plugin to the original jQuery jQueryfnmyplugin = function() thisaddClass(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 Call ing just $(main)open() wont work as open doesnt exist)

      jQuerynoConflict

      Relinquish jQuerys control of the $ variable

      Added in version 10

      jQuerynoConf lict (removeAll)Object

      removeAllBoolean (opt ional) A Boolean indicat ing whether to remove all jQueryvariables f rom the global scope (including jQuery itself )

      Many JavaScript libraries use $ as a funct ion or variable name just as jQuery does In jQueryscase $ is just an alias for jQuery so all funct ionality is available without using $ If we need touse another JavaScript library alongside jQuery we can return control of $ back to the otherlibrary with a call to $noConf lict ()

      ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() Code that uses other l ibrarys $ can follow hereltscriptgt

      This technique is especially ef fect ive in conjunct ion with the ready() methods ability to aliasthe jQuery object as within callback passed to ready() we can use $ if we wish without fear ofconf licts later

      ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() jQuery(document)ready(function($) Code that uses jQuerys $ can follow here ) Code that uses other l ibrarys $ can follow hereltscriptgt

      If necessary we can free up the jQuery name as well by passing true as an argument to themethod This is rarely necessary and if we must do this (for example if we need to use mult ipleversions of the jQuery library on the same page) we need to consider that most plug-ins relyon the presence of the jQuery variable and may not operate correct ly in this situat ion

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

      Javascript

      jQuerynoConfl ict() Do something with jQueryjQuery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

      Example 2 Reverts the $ alias and then creates and executes a funct ion to provide the $ as ajQuery alias inside the funct ions scope Inside the funct ion the original $ object is not availableThis works well for most plugins that dont rely on any other library

      Javascript

      jQuerynoConfl ict()(function($) $(function() more code using $ as alias to jQuery ))(jQuery) other code using $ as an alias to the other l ibrary

      Example 3 You can chain the jQuerynoConf lict () with the shorthand ready for a compact code

      Javascript

      jQuerynoConfl ict()(function() code using jQuery) other code using $ as an alias to the other l ibrary

      Example 4 Creates a dif ferent alias instead of jQuery to use in the rest of the script

      Javascript

      var j = jQuerynoConfl ict() Do something with jQueryj(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

      Example 5 Completely move jQuery to a new namespace in another object

      Javascript

      var dom = domquery = jQuerynoConfl ict(true)

      Results

      Do something with the new jQuerydomquery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none Do something with another version of jQueryjQuery(div gt p)hide()

      jQuery

      Accepts a string containing a CSS selector which is then used to match a set of elements

      Added in version 14

      jQuery()jQuery

      In the f irst formulat ion listed above jQuery() acirceurordquo which can also be writ ten as $() acirceurordquo searchesthrough the DOM for any elements that match the provided selector and creates a new jQueryobject that references these elements

      $(divfoo)

      Selector Context

      By default selectors perform their searches within the DOM start ing at the document rootHowever an alternate context can be given for the search by using the opt ional secondparameter to the $() funct ion For example to do a search within an event handler the searchcan be restricted like so

      $(divfoo)cl ick(function() $(span this)addClass(bar))

      When the search for the span selector is restricted to the context of this only spans within theclicked element will get the addit ional class

      Internally selector context is implemented with the f ind() method so $(span this) is equivalentto $(this)f ind(span)

      Using DOM elements

      The second and third formulat ions of this funct ion create a jQuery object using one or moreDOM elements that were already selected in some other way A common use of this facility isto call jQuery methods on an element that has been passed to a callback funct ion through thekeyword this

      $(divfoo)cl ick(function() $(this)sl ideUp())

      This example causes elements to be hidden with a sliding animat ion when clicked Because thehandler receives the clicked item in the this keyword as a bare DOM element the element mustbe passed to the $() funct ion before applying jQuery methods to it

      XML data returned from an Ajax call can be passed to the $() funct ion so individual elements of

      the XML structure can be retrieved using f ind() and other DOM traversal methods

      $post(urlxml function(data) var $child = $(data)find(child))

      Cloning jQuery Objects

      When a jQuery object is passed to the $() funct ion a clone of the object is created This newjQuery object references the same DOM elements as the init ial one

      Returning an Empty Set

      As of jQuery 14 calling the jQuery() method with no arguments returns an empty jQuery set(with a length property of 0) In previous versions of jQuery this would return a set containingthe document node

      Example 1 Find all p elements that are children of a div element and apply a border to them

      Javascript

      $(div gt p)css(border 1px solid gray)

      HTML

      ltpgtoneltpgt ltdivgtltpgttwoltpgtltdivgt ltpgtthreeltpgt

      Example 2 Find all inputs of type radio within the f irst form in the document

      Javascript

      $(inputradio documentforms[0])

      Example 3 Find all div elements within an XML document f rom an Ajax response

      Javascript

      $(div xmlresponseXML)

      Example 4 Set the background color of the page to black

      Javascript

      $(documentbody)css( background black )

      Example 5 Hide all the input elements within a form

      Javascript

      $(myFormelements)hide()

      jQuery

      Creates DOM elements on the f ly f rom the provided string of raw HTML

      Added in version 14

      jQuery(html props)jQuery

      htmlString A string def ining a single standalone HTML element (eg ltdivgt orltdivgtltdivgt)

      propsObject An map of at t ributes events and methods to call on the newly-createdelement

      Creating New Elements

      If a string is passed as the parameter to $() jQuery examines the string to see if it looks likeHTML (ie it has lttag gt somewhere within the string) If not the string is interpreted as aselector expression as explained above But if the string appears to be an HTML snippetjQuery at tempts to create new DOM elements as described by the HTML Then a jQuery objectis created and returned that refers to these elements You can perform any of the usual jQuerymethods on this object

      $(ltp id=testgtMy ltemgtnewltemgt textltpgt)appendTo(body)

      If the HTML is more complex than a single tag without at t ributes as it is in the above examplethe actual creat ion of the elements is handled by the browsers innerHTML mechanism In mostcases jQuery creates a new

      element and sets the innerHTML property of the element to the HTML snippet that was passedin When the parameter has a single tag such as$(ltimgAcirc gt) or $(ltagtltagt) jQuery creates the element using the nat ive JavaScriptcreateElement() funct ion

      When passing in complex HTML some browsers may not generate a DOM that exact ly

      replicates the HTML source provided As ment ioned we use the browsers innerHTML propertyto parse the passed HTML and insert it into the current document During this process somebrowsers f ilter out certain elements such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements inserted may not be representat ive of the original string passed

      Filtering isnt however just limited to these tags For example Internet Explorer prior to version 8will also convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

      To ensure cross-plat form compat ibility the snippet must be well-formed Tags that can containother elements should be paired with a closing tag

      $(lta href=httpjquerycomgtltagt)

      Alternat ively jQuery allows XML-like tag syntax (with or without a space before the slash)

      $(ltagt)

      Tags that cannot contain elements may be quick-closed or not

      $(ltimg gt)$(ltinputgt)

      When passing HTML to jQuery() please also note that text nodes are not t reated as DOMelements With the except ion of a few methods (such as content()) they are generallyotherwise ignored or removed Eg

      var el = $(1ltbrgt2ltbrgt3) returns [ltbrgt 2 ltbrgt] el = $(1ltbrgt2ltbrgt3 gt) returns [ltbrgt 2 ltbrgt 3 ampgt]

      This behaviour is expected

      As of jQuery 14 the second argument to jQuery() can accept a map consist ing of a supersetof the propert ies that can be passed to the at t r() method Furthermore any event type can bepassed in and the following jQuery methods can be called val css html text data widthheight or of fset The name class must be quoted in the map since it is a JavaScript reservedword and className cannot be used since it is not the correct at t ribute name

      Note Internet Explorer will not allow you to create an input or button element and change itstype you must specify the type using ltinput type=checkbox gt for example A demonstrat ionof this can be seen below

      Unsupported in IE

      $(ltinput gt type text name test)appendTo(body)

      Supported workaround

      $(ltinput type=text gt)attr( name test)appendTo(body)

      Example 1 Create a div element (and all of its contents) dynamically and append it to the bodyelement Internally an element is created and its innerHTML property set to the given markup

      Javascript

      $(ltdivgtltpgtHelloltpgtltdivgt)appendTo(body)

      Example 2 Create some DOM elements

      Javascript

      $(ltdivgt class test text Click me cl ick function() $(this)toggleClass(test) )appendTo(body)

      jQuery

      Binds a funct ion to be executed when the DOM has f inished loading

      Added in version 10

      jQuery(callback)jQuery

      callbackFunct ion The funct ion to execute when the DOM is ready

      This funct ion behaves just like $(document)ready() in that it should be used to wrap other $()operat ions on your page that depend on the DOM being ready While this funct ion is

      technically chainable there really isnt much use for chaining against it

      Example 1 Execute the funct ion when the DOM is ready to be used

      Javascript

      $(function() Document is ready )

      Example 2 Use both the shortcut for $(document)ready() and the argument to write failsafejQuery code using the $ alias without relying on the global alias

      Javascript

      jQuery(function($) Your code using failsafe $ alias here )

      Selectors

      focus $(focus)

      Selects element if it is current ly focused

      Added in version 16

      $(focus)

      As with other pseudo-class selectors (those that begin with a ) it is recommended toprecede focus with a tag name or some other selector otherwise the universal selector () isimplied In other words the bare $(focus) is equivalent to $(focus) If you are looking for thecurrent ly focused element $( documentact iveElement ) will retrieve it without having to searchthe whole DOM tree

      Example 1 Adds the focused class to whatever element has focus

      Javascript

      $()l ive(focus blur function(e) var el = $(this) setTimeout(function() eltoggleClass(focused elis(focus)) 0))

      CSS

      focused background abcdef

      HTML

      ltinput tabIndex=1gtltinput tabIndex=2gtltselect tabIndex=3gt ltoptiongtselect menultoptiongtltselectgtltdiv tabIndex=4gt a divltdivgt

      selected $(selected)

      Selects all elements that are selected

      Added in version 10

      $(selected)

      The selected selector works for ltopt iongt elements It does not work for checkboxes or radioinputs use checked for them

      Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

      Javascript

      $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) trigger(change)

      CSS

      div colorred

      HTML

      ltselect name=garden multiple=multiplegt

      ltoptiongtFlowersltoptiongt ltoption selected=selectedgtShrubsltoptiongt ltoptiongtTreesltoptiongt ltoption selected=selectedgtBushesltoptiongt

      ltoptiongtGrassltoptiongt ltoptiongtDirtltoptiongt ltselectgt ltdivgtltdivgt

      checked $(checked)

      Matches all elements that are checked

      Added in version 10

      $(checked)

      The checked selector works for checkboxes and radio buttons For select elements use theselected selector

      Example 1 Finds all input elements that are checked

      Javascript

      function countChecked() var n = $(inputchecked)length $(div)text(n + (n lt= 1 is are) + checked)countChecked()$(checkbox)cl ick(countChecked)

      CSS

      div colorred

      HTML

      ltformgt ltpgt ltinput type=checkbox name=newsletter checked=checked value=Hourly gt

      ltinput type=checkbox name=newsletter value=Daily gt ltinput type=checkbox name=newsletter value=Weekly gt

      ltinput type=checkbox name=newsletter checked=checked value=Monthly gt ltinput type=checkbox name=newsletter value=Yearly gt ltpgtltformgtltdivgtltdivgt

      Example 2

      Javascript

      $(input)cl ick(function() $(log)html( $(checked)val() + is checked ))

      CSS

      input label l ine-height 15em

      HTML

      ltformgt ltdivgt ltinput type=radio name=fruit value=orange id=orangegt ltlabel for=orangegtorangeltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=apple id=applegt ltlabel for=applegtappleltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=banana id=bananagt ltlabel for=bananagtbananaltlabelgt ltdivgt ltdiv id=loggtltdivgtltformgt

      disabled $(disabled)

      Selects all elements that are disabled

      Added in version 10

      $(disabled)

      As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(disabled) is equivalent to $(disabled) so $(inputdisabled) should beused instead

      Example 1 Finds all input elements that are disabled

      Javascript

      $(inputdisabled)val(this is it)

      HTML

      ltformgt

      ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

      enabled $(enabled)

      Selects all elements that are enabled

      Added in version 10

      $(enabled)

      As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(enabled) is equivalent to $(enabled) so $(inputenabled) should beused instead

      Example 1 Finds all input elements that are enabled

      Javascript

      $(inputenabled)val(this is it)

      HTML

      ltformgt

      ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

      file $(file)

      Selects all elements of type f ile

      Added in version 10

      $(f ile)

      f ile is equivalent to [type=f ile] 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 theuniversal selector () is implied In other words the bare $(f ile) is equivalent to $(f ile) so$(inputf ile) should be used instead

      Example 1 Finds all f ile inputs

      Javascript

      var input = $(inputfi le)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height45px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      button $(button)

      Selects all but ton elements and elements of type button

      Added in version 10

      $(button)

      Example 1 Finds all but ton inputs

      Javascript

      var input = $(button)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height45px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      reset $(reset)

      Selects all elements of type reset

      Added in version 10

      $(reset)

      reset is equivalent to [type=reset]

      Example 1 Finds all reset inputs

      Javascript

      var input = $(inputreset)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height45px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      image $(image)

      Selects all elements of type image

      Added in version 10

      $(image)

      image is equivalent to [type=image]

      Example 1 Finds all image inputs

      Javascript

      var input = $(inputimage)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height45px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      submit $(submit)

      Selects all elements of type submit

      Added in version 10

      $(submit)

      The submit selector typically applies to button or input elements Note that some browserstreat ltbuttongt element as type=default implicit ly while others (such as Internet Explorer) donot

      Example 1 Finds all submit elements that are descendants of a td element

      Javascript

      var submitEl = $(td submit) parent(td) css(backgroundyellow border3px red solid) end() $(result)text( jQuery matched + submitEllength + elements)

      so it wont 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 = inputElattr(type) type= + inputElattr(type) + $(el)before(lttdgt + inputEl[0]nodeName + inputType + lttdgt) )

      CSS

      textarea height45px

      HTML

      lttablegtltformgtlttable id=exampleTable border=1 cellpadding=10 align=centergt

      lttrgt ltthgt Element Type ltthgt ltthgt Element ltthgt

      lttr lttrgt lttdgt ltinput type=button value=Input Buttongt lttdgt

      lttrgt lttrgt lttdgt ltinput type=checkbox gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=fi le gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=hidden gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=image gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=password gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=radio gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=reset gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=submit gt lttdgt

      lttrgt lttrgt lttdgt ltinput type=text gt lttdgt

      lttrgt lttrgt lttdgt ltselectgtltoptiongtOptionltoptiongtltselectgt lttdgt

      lttrgt lttrgt lttdgt lttextareagtlttextareagt lttdgt lttrgt

      lttrgt lttdgt ltbuttongtButtonltbuttongt lttdgt lttrgt lttrgt lttdgt ltbutton type=submitgtButton type=submitltbuttongt lttdgt lttrgt

      lttablegtltformgtltdiv id=resultgtltdivgt

      checkbox $(checkbox)

      Selects all elements of type checkbox

      Added in version 10

      $(checkbox)

      $(checkbox) is equivalent to $([type=checkbox]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(checkbox) isequivalent to $(checkbox) so $(inputcheckbox) should be used instead

      Example 1 Finds all checkbox inputs

      Javascript

      var input = $(form inputcheckbox)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height25px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=checkbox gt ltinput type=fi le gt ltinput type=hidden gt

      ltinput type=image gt ltinput type=password gt ltinput type=radio gt

      ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

      ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

      ltdivgt ltdivgt

      radio $(radio)

      Selects all elements of type radio

      Added in version 10

      $(radio)

      $(radio) is equivalent to $([type=radio]) As with other pseudo-class selectors (those thatbegin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(radio) is equivalentto $(radio) so $(inputradio) should be used instead

      To select a set of associated radio buttons you might use $(input[name=gender]radio)

      Example 1 Finds all radio inputs

      Javascript

      var input = $(form inputradio)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height25px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio name=asdf gt ltinput type=radio name=asdf gt

      ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

      ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

      ltdivgt ltdivgt

      password $(password)

      Selects all elements of type password

      Added in version 10

      $(password)

      $(password) is equivalent to $([type=password]) As with other pseudo-class selectors (thosethat 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 $(password) isequivalent to $(password) so $(inputpassword) should be used instead

      Example 1 Finds all password inputs

      Javascript

      var input = $(inputpassword)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height45px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      text $(text)

      Selects all elements of type text

      Added in version 10

      $(text)

      $(text ) is equivalent to $([type=text ]) and thus selects all ltinput type=textgt elements Aswith other pseudo-class selectors (those that begin with a ) it is recommended to precede itwith a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(text ) is equivalent to $(text ) so $(inputtext ) should be usedinstead

      Note As of jQuery 152 text selects input elements that have no specif ied type at t ribute (inwhich case type=text is implied)

      Example 1 Finds all text inputs

      Javascript

      var input = $(form inputtext)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

      CSS

      textarea height25px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

      input $(input)

      Selects all input textarea select and button elements

      Added in version 10

      $(input)

      The input selector basically selects all form controls

      Example 1 Finds all input elements

      Javascript

      var all Inputs = $(input) var formChildren = $(form gt ) $(messages)text(Found + all Inputslength + inputs and the form has + formChildrenlength + children) so it wont submit $(form)submit(function () return false )

      CSS

      textarea height25px

      HTML

      ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

      ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

      ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

      ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

      lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdiv id=messagesgt ltdivgt

      only-child $(only-child)

      Selects all elements that are the only child of their parent

      Added in version 114

      $(only-child)

      If the parent has other child elements nothing is matched

      Example 1 Change the text and add a border for each button that is the only child of its parent

      Javascript

      $(div buttononly-child)text(Alone)css(border 2px blue solid)

      CSS

      div width100px height80px margin5px floatleft backgroundb9e

      HTML

      ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongtltdivgt

      ltdivgt ltbuttongtSiblingltbuttongtltdivgtltdivgt Noneltdivgt

      ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt

      ltdivgtltdivgt ltbuttongtSiblingltbuttongtltdivgt

      last-child $(last-child)

      Selects all elements that are the last child of their parent

      Added in version 114

      $(last-child)

      While last matches only a single element last-child can match more than one one for eachparent

      Example 1 Finds the last span in each matched div and adds some css plus a hover state

      Javascript

      $(div spanlast-child) css(colorred fontSize80) hover(function () $(this)addClass(solast) function () $(this)removeClass(solast) )

      CSS

      spansolast text-decorationl ine-through

      HTML

      ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

      ltspangtSamltspangt ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt

      ltspangtRalphltspangt ltspangtDavidltspangt ltdivgt

      first-child $(first-child)

      Selects all elements that are the f irst child of their parent

      Added in version 114

      $(f irst-child)

      While f irst matches only a single element the f irst-child selector can match more than oneone for each parent This is equivalent to nth-child(1)

      Example 1 Finds the f irst span in each matched div to underline and add a hover state

      Javascript

      $(div spanfirst-child) css(text-decoration underline) hover(function () $(this)addClass(sogreen) function () $(this)removeClass(sogreen) )

      CSS

      span color008 spansogreen colorgreen font-weight bolder

      HTML

      ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

      ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt ltspangtRalphltspangt

      ltdivgt

      nth-child $(nth-child(indexevenoddequation))

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

      Added in version 114

      $(nth-child(indexevenoddequat ion))

      indexNumberString The index of each child to match start ing with 1 the string evenor odd or an equat ion ( eg nth-child(even) nth-child(4n) )

      Because jQuerys implementat ion of nth-child(n) is strict ly derived from the CSS specif icat ionthe value of n is 1-indexed meaning that the count ing starts at 1 For all other selectorexpressions however jQuery follows JavaScript s 0-indexed count ing Therefore given asingle ltulgt containing two ltligts $(linth-child(1)) selects the f irst ltligt while $(lieq(1)) selectsthe second

      The nth-child(n) pseudo-class is easily confused with eq(n) even though the two can result indramat ically dif ferent matched elements With nth-child(n) all children are counted regardlessof what they are and the specif ied element is selected only if it matches the selector at tachedto the pseudo-class With eq(n) only the selector at tached to the pseudo-class is counted notlimited 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 W3C CSS specif icat ion

      Example 1 Finds the second li in each matched ul and notes it

      Javascript

      $(ul l i nth-child(2))append(ltspangt - 2ndltspangt)

      CSS

      div floatleft span colorblue

      HTML

      ltdivgtltulgt ltligtJohnltligt ltligtKarlltl igt ltligtBrandonltligt

      ltulgtltdivgt ltdivgtltulgt ltligtSamltligt ltulgtltdivgt

      ltdivgtltulgt ltligtGlenltligt ltligtTaneltligt ltligtRalphltligt

      ltligtDavidltligt ltulgtltdivgt

      Example 2 This is a playground to see how the selector works with dif ferent strings Not icethat this is dif ferent f rom the even and odd which have no regard for parent and just f ilter thelist of elements to every other one The nth-child however counts the index of the child to itspart icular parent In any case it s easier to see than explain so

      Javascript

      $(button)cl ick(function () var str = $(this)text() $(tr)css(background white) $(tr + str)css(background ff0000) $(inner)text(str) )

      CSS

      button displayblock font-size12px width100px div floatleft margin10px font-size10px border1px solid black span colorblue font-size18px inner colorred td width50px text-aligncenter

      HTML

      ltdivgt ltbuttongtnth-child(even)ltbuttongt ltbuttongtnth-child(odd)ltbuttongt ltbuttongtnth-child(3n)ltbuttongt

      ltbuttongtnth-child(2)ltbuttongt ltdivgt ltdivgt ltbuttongtnth-child(3n+1)ltbuttongt ltbuttongtnth-child(3n+2)ltbuttongt

      ltbuttongtevenltbuttongt ltbuttongtoddltbuttongt ltdivgt ltdivgtlttablegt

      lttrgtlttdgtJohnlttdgtlttrgt lttrgtlttdgtKarllttdgtlttrgt lttrgtlttdgtBrandonlttdgtlttrgt

      lttrgtlttdgtBenjaminlttdgtlttrgt lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtSamlttdgtlttrgt

      lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtGlenlttdgtlttrgt lttrgtlttdgtTanelttdgtlttrgt

      lttrgtlttdgtRalphlttdgtlttrgt lttrgtlttdgtDavidlttdgtlttrgt lttrgtlttdgtMikelttdgtlttrgt

      lttrgtlttdgtDanlttdgtlttrgt lttablegtltdivgt ltspangt trltspan id=innergtltspangt

      ltspangt

      attributeContainsPrefix $([attribute|=value])

      Selects elements that have the specif ied at t ribute with a value either equal to a given string orstart ing with that string followed by a hyphen (-)

      Added in version 10

      $([at t ribute|=value])

      attributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      This selector was introduced into the CSS specif icat ion to handle language at t ributes

      Example 1 Finds all links with an href lang at t ribute that is english

      Javascript

      $(a[hreflang|=en])css(border3px dotted green)

      HTML

      lta href=examplehtml hreflang=engtSome textltagt

      lta href=examplehtml hreflang=en-UKgtSome other textltagt

      lta href=examplehtml hreflang=englishgtwill not be outl inedltagt

      CSS

      a display inl ine-block

      attributeContainsWord $([attribute~=value])

      Selects elements that have the specif ied at t ribute with a value containing a given worddelimited by spaces

      Added in version 10

      $([at t ribute~=value])

      at t ributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      This selector matches the test string against each word in the at t ribute value where a word isdef ined as a string delimited by whitespace The selector matches if the test string is exact lyequal to any of the words

      Example 1 Finds all inputs with a name attribute that contains the word man and sets the

      value with some text

      Javascript

      $( input[name~=man])val(mr man is in it)

      HTML

      ltinput name=man-news gt

      ltinput name=milk man gt ltinput name=letterman2 gt ltinput name=newmilk gt

      attributeMultiple$([attributeFilter1][attributeFilter2][attributeFilterN])

      Matches elements that match all of the specif ied at t ribute f ilters

      Added in version 10

      $([at t ributeFilter1][at t ributeFilter2][at t ributeFilterN])

      at t ributeFilter1Selector An at t ribute f ilter

      at t ributeFilter2Selector Another at t ribute f ilter reducing the select ion even more

      attributeFilterNSelector (opt ional) As many more at t ribute f ilters as necessary

      Example 1 Finds all inputs that have an id at t ribute and whose name attribute ends with manand sets the value

      Javascript

      $( input[id][name$=man])val(only this one)

      HTML

      ltinput id=man-news name=man-news gt

      ltinput name=milkman gt ltinput id=letterman name=new-letterman gt ltinput name=newmilk gt

      attributeContains $([attribute=value])

      Selects elements that have the specif ied at t ribute with a value containing the a given substring

      Added in version 10

      $([at t ribute=value])

      at t ributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      This is the most generous of the jQuery at t ribute selectors that match against a value It willselect an element if the selectors string appears anywhere within the element s at t ribute valueCompare this selector with the Attribute Contains Word selector (eg [at t r~=word]) which ismore appropriate in many cases

      Example 1 Finds all inputs with a name attribute that contains man and sets the value withsome text

      Javascript

      $( input[name=man])val(has man in it)

      HTML

      ltinput name=man-news gt

      ltinput name=milkman gt ltinput name=letterman2 gt ltinput name=newmilk gt

      attributeEndsWith $([attribute$=value])

      Selects elements that have the specif ied at t ribute with a value ending exact ly with a givenstring The comparison is case sensit ive

      Added in version 10

      $([at t ribute$=value])

      at t ributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      Example 1 Finds all inputs with an at t ribute name that ends with let ter and puts text in them

      Javascript

      $( input[name$=letter])val(a letter)

      HTML

      ltinput name=newsletter gt

      ltinput name=milkman gt ltinput name=jobletter gt

      attributeStartsWith $([attribute^=value])

      Selects elements that have the specif ied at t ribute with a value beginning exact ly with a givenstring

      Added in version 10

      $([at t ribute^=value])

      at t ributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      This selector can be useful for ident ifying elements in pages produced by server-sideframeworks that produce HTML with systemat ic element IDs However it will be slower thanusing a class selector so leverage classes if you can to group like elements

      Example 1 Finds all inputs with an at t ribute name that starts with news and puts text in them

      Javascript

      $( input[name^=news])val(news here)

      HTML

      ltinput name=newsletter gt

      ltinput name=milkman gt ltinput name=newsboy gt

      attributeNotEqual $([attribute=value])

      Select elements that either dont have the specif ied at t ribute or do have the specif ied at t ributebut not with a certain value

      Added in version 10

      $([at t ribute=value])

      at t ributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      This selector is equivalent to not([at t r=value])

      Example 1 Finds all inputs that dont have the name newslet ter and appends text to the spannext to it

      Javascript

      $( input[name=newsletter])next()append(ltbgt not newsletterltbgt)

      HTML

      ltdivgt

      ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtname is newsletterltspangt

      ltdivgt ltdivgt ltinput type=radio value=Cold Fusion gt ltspangtno nameltspangt

      ltdivgt ltdivgt ltinput type=radio name=accept value=Evil Plans gt

      ltspangtname is acceptltspangt ltdivgt

      attributeEquals $([attribute=value])

      Selects elements that have the specif ied at t ribute with a value exact ly equal to a certain value

      Added in version 10

      $([at t ribute=value])

      attributeString An at t ribute name

      valueString An at t ribute value Quotes are mandatory

      Example 1 Finds all inputs with a value of Hot Fuzz and changes the text of the next siblingspan

      Javascript

      $( input[value=Hot Fuzz])next()text( Hot Fuzz)

      HTML

      ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtnameltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Cold Fusion gt ltspangtvalueltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Evil Plans gt ltspangtvalueltspangt ltlabelgt ltdivgt

      attributeHas $([attribute])

      Selects elements that have the specif ied at t ribute with any value

      Added in version 10

      $([at t ribute])

      at t ributeString An at t ribute name

      Example 1 Bind a single click that adds the div id to its text

      Javascript

      $(div[id])one(cl ick function() var idString = $(this)text() + = + $(this)attr( id) $(this)text(idString) )

      HTML

      ltdivgtno idltdivgt ltdiv id=heygtwith idltdivgt

      ltdiv id=theregthas an idltdivgt ltdivgtnopeltdivgt

      visible $(visible)

      Selects all elements that are visible

      Added in version 10

      $(visible)

      Elements can be considered hidden for several reasons

      They have a CSS display value of none

      They are form elements with type=hidden

      Their width and height are explicit ly set to 0

      An ancestor element is hidden so the element is not shown on the page

      Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start at the animat ion

      How visible is calculated was changed in jQuery 132 The release notes out line the changes inmore detail

      Example 1 Make all visible divs turn yellow on click

      Javascript

      $(divvisible)cl ick(function () $(this)css(background yellow) ) $(button)cl ick(function () $(divhidden)show(fast) )

      CSS

      div width50px height40px margin5px border3px outset green floatleft starthidden displaynone

      HTML

      ltbuttongtShow hidden to see they dont changeltbuttongt ltdivgtltdivgt ltdiv class=starthiddengtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdiv style=displaynonegtltdivgt

      hidden $(hidden)

      Selects all elements that are hidden

      Added in version 10

      $(hidden)

      Elements can be considered hidden for several reasons

      They have a CSS display value of none

      They are form elements with type=hidden

      Their width and height are explicit ly set to 0

      An ancestor element is hidden so the element is not shown on the page

      Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start of the animat ion

      How hidden is determined was changed in jQuery 132 An element is assumed to be hidden if itor any of its parents consumes no space in the document CSS visibility isnt taken into account(therefore $(elem)css(visibilityhidden)is(hidden) == false) The release notes out line thechanges in more detail

      Example 1 Shows all hidden divs and counts hidden inputs

      Javascript

      in some browsers hidden includes head title script etcvar hiddenEls = $(body)find(hidden)not(script)

      $(spanfirst)text(Found + hiddenElslength + hidden elements total)$(divhidden)show(3000)$(spanlast)text(Found + $(inputhidden)length + hidden inputs)

      CSS

      div width70px height40px backgroundee77ff margin5px floatleft span displayblock clearleft colorred starthidden displaynone

      HTML

      ltspangtltspangt ltdivgtltdivgt ltdiv style=displaynonegtHiderltdivgt ltdivgtltdivgt

      ltdiv class=starthiddengtHiderltdivgt ltdivgtltdivgt ltformgt ltinput type=hidden gt

      ltinput type=hidden gt ltinput type=hidden gt ltformgt ltspangt

      ltspangt

      parent $(parent)

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

      Added in version 10

      $(parent)

      This is the inverse of empty

      One important thing to note regarding the use of parent (and empty) is that child elementsinclude text nodes

      The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elements

      on the other hand are empty (ie have no children) by def init ion ltinputgt ltimggt ltbrgt and lthrgtfor example

      Example 1 Finds all tds with children including text

      Javascript

      $(tdparent)fadeTo(1500 03)

      CSS

      td width40px backgroundgreen

      HTML

      lttable border=1gt

      lttrgtlttdgtValue 1lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtValue 2lttdgtlttdgtlttdgtlttrgt

      lttablegt

      has $(has(selector))

      Selects elements which contain at least one element that matches the specif ied selector

      Added in version 114

      $(has(selector))

      selectorSelector Any selector

      The expression $(divhas(p)) matches a ltdivgt if a ltpgt exists anywhere among its descendantsnot just as a direct child

      Example 1 Adds the class test to all divs that have a paragraph inside of them

      Javascript

      $(divhas(p))addClass(test)

      HTML

      ltdivgtltpgtHello in a paragraphltpgtltdivgt

      ltdivgtHello again (with no paragraph)ltdivgt

      CSS

      test border 3px inset red

      empty $(empty)

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

      Added in version 10

      $(empty)

      This is the inverse of parent

      One important thing to note with empty (and parent) is that child elements include text nodes

      The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elementson the other hand are empty (ie have no children) by def init ion and

      for example

      Example 1 Finds all elements that are empty - they dont have child elements or text

      Javascript

      $(tdempty)text(Was empty)css(background rgb(255220200))

      CSS

      td text-aligncenter

      HTML

      lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtTD 2lttdgtlttdgtlttdgtlttrgt

      lttrgtlttdgtlttdgtlttdgtTD5lttdgtlttrgt lttablegt

      contains $(contains(text))

      Select all elements that contain the specif ied text

      Added in version 114

      $(contains(text))

      text String A string of text to look for It s case sensit ive

      The matching text can appear direct ly within the selected element in any of that element sdescendants or a combinat ion thereof As with at t ribute value selectors text inside theparentheses of contains() can be writ ten as bare words or surrounded by quotat ion marks Thetext must have matching case to be selected

      Example 1 Finds all divs containing John and underlines them

      Javascript

      $(divcontains( John))css(text-decoration underline)

      HTML

      ltdivgtJohn Resigltdivgt

      ltdivgtGeorge MartinltdivgtltdivgtMalcom John SinclairltdivgtltdivgtJ Ohnltdivgt

      animated $(animated)

      Select all elements that are in the progress of an animat ion at the t ime the selector is run

      Added in version 12

      $(animated)

      Example 1 Change the color of any div that is animated

      Javascript

      $(run)cl ick(function() $(divanimated)toggleClass(colored) ) function animateIt() $(mover)sl ideToggle(slow animateIt) animateIt()

      HTML

      ltbutton id=rungtRunltbuttongt

      ltdivgtltdivgt ltdiv id=movergtltdivgt ltdivgtltdivgt

      CSS

      div backgroundyellow border1px solid AAA width80px height80px margin0 5px floatleft divcolored backgroundgreen

      header $(header)

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

      Added in version 12

      $(header)

      Example 1 Adds a background and text color to all the headers on the page

      Javascript

      $(header)css( backgroundCCC colorblue )

      HTML

      lth1gtHeader 1lth1gt

      ltpgtContents 1ltpgt lth2gtHeader 2lth2gt ltpgtContents 2ltpgt

      CSS

      body font-size 10px font-family Arial h1 h2 margin 3px 0

      lt $(lt(index))

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

      Added in version 10

      $(lt (index))

      indexNumber Zero-based index

      index-related selectors

      The index-related selectors (including this less than selector) f ilter the set of elements thathave matched the expressions that precede them They narrow the set down based on theorder of the elements within this matched set For example if elements are f irst selected with aclass selector (myclass) and four elements are returned these elements are given indices 0through 3 for the purposes of these selectors

      Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasslt (1)) selects the f irst element in the document with the class myclass ratherthan select ing no elements In contrast nth-child(n) uses 1-based indexing to conform to theCSS specif icat ion

      Example 1 Finds TDs less than the one with the 4th index (TD4)

      Javascript

      $(tdlt(4))css(color red)

      HTML

      lttable border=1gt

      lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

      lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

      gt $(gt(index))

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

      Added in version 10

      $(gt(index))

      indexNumber Zero-based index

      index-related selectors

      The index-related selector expressions (including this greater than selector) f ilter the set ofelements that have matched the expressions that precede them They narrow the set downbased on the order of the elements within this matched set For example if elements are f irstselected with a class selector (myclass) and four elements are returned these elements aregiven indices 0 through 3 for the purposes of these selectors

      Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclassgt(1)) selects elements af ter the second element in the document with theclass myclass rather than af ter the f irst In contrast nth-child(n) uses 1-based indexing toconform to the CSS specif icat ion

      Example 1 Finds TD 5 and higher Reminder the indexing starts at 0

      Javascript

      $(tdgt(4))css(text-decoration l ine-through)

      HTML

      lttable border=1gt

      lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

      lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgt lttablegt

      eq $(eq(index))

      Select the element at index n within the matched set

      Added in version 10

      $(eq(index))

      indexNumber Zero-based index of the element to match

      The index-related selectors (eq() lt () gt() even odd) f ilter the set of elements that havematched the expressions that precede them They narrow the set down based on the order ofthe elements within this matched set For example if elements are f irst selected with a classselector (myclass) and four elements are returned these elements are given indices 0 through3 for the purposes of these selectors

      Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasseq(1)) selects the second element in the document with the class myclassrather than the f irst In contrast nth-child(n) uses 1-based indexing to conform to the CSSspecif icat ion

      Unlike the eq(index) method the eq(index) selector does not accept a negat ive value for indexFor example while $(li)eq(-1) selects the last li element $(lieq(-1)) selects nothing

      Example 1 Finds the third td

      Javascript

      $(tdeq(2))css(color red)

      HTML

      lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

      Example 2 Apply three dif ferent styles to list items to demonstrate that eq() is designed toselect a single element while nth-child() or eq() within a looping construct such as each() canselect mult iple elements

      Javascript

      applies yellow background color to a single ltligt$(ulnav l i eq(1))css( backgroundColor ff0 )

      applies ital ics to text of the second ltligt within each ltul class=navgt$(ulnav)each(function(index) $(this)find(l i eq(1))css( fontStyle ital ic ))

      applies red text color to descendants of ltul class=navgt for each ltligt that is the second child of its parent$(ulnav l i nth-child(2))css( color red )

      HTML

      ltul class=navgt ltligtList 1 item 1ltligt ltligtList 1 item 2ltligt ltligtList 1 item 3ltligtltulgtltul class=navgt ltligtList 2 item 1ltligt ltligtList 2 item 2ltligt ltligtList 2 item 3ltligtltulgt

      odd $(odd)

      Selects odd elements zero-indexed See also even

      Added in version 10

      $(odd)

      In part icular note that the 0-based indexing means that counter-intuit ively odd selects thesecond element fourth element and so on within the matched set

      Example 1 Finds odd table rows matching the second fourth and so on (index 1 3 5 etc)

      Javascript

      $(trodd)css(background-color bbbbff)

      CSS

      table backgroundf3f7f5

      HTML

      lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

      lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

      even $(even)

      Selects even elements zero-indexed See also odd

      Added in version 10

      $(even)

      In part icular note that the 0-based indexing means that counter-intuit ively even selects thef irst element third element and so on within the matched set

      Example 1 Finds even table rows matching the f irst third and so on (index 0 2 4 etc)

      Javascript

      $(treven)css(background-color bbbbff)

      CSS

      table backgroundeeeeee

      HTML

      lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

      lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

      not $(not(selector))

      Selects all elements that do not match the given selector

      Added in version 10

      $(not(selector))

      selectorSelector A selector with which to f ilter by

      All selectors are accepted inside not() for example not(div a) and not(diva)

      Additional Notes

      The not() method will end up providing you with more readable select ions than pushingcomplex selectors or variables into a not() selector f ilter In most cases it is a better choice

      Example 1 Finds all inputs that are not checked and highlights the next sibling span Not icethere is no change when clicking the checkboxes since no click events have been linked

      Javascript

      $(inputnot(checked) + span)css(background-color yellow) $(input)attr(disabled disabled)

      HTML

      ltdivgt ltinput type=checkbox name=a gt ltspangtMaryltspangtltdivgt

      ltdivgt ltinput type=checkbox name=b gt ltspangtlcmltspangt

      ltdivgtltdivgt ltinput type=checkbox name=c checked=checked gt

      ltspangtPeterltspangtltdivgt

      last $(last)

      Selects the last matched element

      Added in version 10

      $(last)

      Note that last selects a single element by f iltering the current jQuery collect ion and matchingthe last element within it

      Example 1 Finds the last table row

      Javascript

      $(trlast)css(backgroundColor yellow fontWeight bolder)

      HTML

      lttablegt

      lttrgtlttdgtFirst Rowlttdgtlttrgt lttrgtlttdgtMiddle Rowlttdgtlttrgt lttrgtlttdgtLast Rowlttdgtlttrgt

      lttablegt

      first $(first)

      Selects the f irst matched element

      Added in version 10

      $(f irst)

      The f irst pseudo-class is equivalent to eq(0) It could also be writ ten as lt (1) While thismatches only a single element f irst-child can match more than one One for each parent

      Example 1 Finds the f irst table row

      Javascript

      $(trfirst)css(font-style ital ic)

      CSS

      td colorblue font-weightbold

      HTML

      lttablegt lttrgtlttdgtRow 1lttdgtlttrgt lttrgtlttdgtRow 2lttdgtlttrgt

      lttrgtlttdgtRow 3lttdgtlttrgt lttablegt

      next siblings $(prev ~ siblings)

      Selects all sibling elements that follow af ter the prev element have the same parent andmatch the f iltering siblings selector

      Added in version 10

      $(prev ~ siblings)

      prevSelector Any valid selector

      siblingsSelector A selector to f ilter elements that are the following siblings of the f irstselector

      The notable dif ference between (prev + next) and (prev ~ siblings) is their respect ive reachWhile the former reaches only to the immediately following sibling element the lat ter extendsthat reach to all following sibling elements

      Example 1 Finds all divs that are siblings af ter the element with prev as its id Not ice the spanisnt selected since it is not a div and the niece isnt selected since it is a child of a sibling notan actual sibling

      Javascript

      $(prev ~ div)css(border 3px groove blue)

      CSS

      divspan displayblock width80px height80px margin5px backgroundbbffaa floatleft font-size14px divsmall width60px height25px font-size12px backgroundfab

      HTML

      ltdivgtdiv (doesnt match since before prev)ltdivgt ltspan id=prevgtspanprevltspangt ltdivgtdiv siblingltdivgt

      ltdivgtdiv sibling ltdiv id=smallgtdiv nieceltdivgtltdivgt ltspangtspan sibling (not div)ltspangt ltdivgtdiv siblingltdivgt

      next adjacent $(prev + next)

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

      Added in version 10

      $(prev + next)

      prevSelector Any valid selector

      nextSelector A selector to match the element that is next to the f irst selector

      One important point to consider with both the next adjacent sibling selector (prev + next) andthe general sibling selector (prev ~ siblings) is that the elements on either side of thecombinator must share the same parent

      Example 1 Finds all inputs that are next to a label

      Javascript

      $(label + input)css(color blue)val(Labeled)

      HTML

      ltformgt

      ltlabelgtNameltlabelgt ltinput name=name gt ltfieldsetgt ltlabelgtNewsletterltlabelgt

      ltinput name=newsletter gt ltfieldsetgt ltformgt ltinput name=none gt

      child $(parent gt child)

      Selects all direct child elements specif ied by child of elements specif ied by parent

      Added in version 10

      $(parent gt child)

      parentSelector Any valid selector

      childSelector A selector to f ilter the child elements

      As a CSS selector the child combinator is supported by all modern web browsers includingSafari Firefox Opera Chrome and Internet Explorer 7 and above but notably not by InternetExplorer versions 6 and below However in jQuery this selector (along with all others) worksacross all supported browsers including IE6

      The child combinator (E gt F) can be thought of as a more specif ic form of the descendantcombinator (E F) in that it selects only f irst-level descendants

      Note The $(gt elem context) selector will be deprecated in a future release Itsusage is thus discouraged in lieu of using alternative selectors

      Example 1 Places a border around all list items that are children of

      Javascript

      $(ultopnav gt l i)css(border 3px double red)

      CSS

      body font-size14px

      HTML

      ltul class=topnavgt ltligtItem 1ltligt ltligtItem 2 ltulgtltligtNested item 1ltligtltligtNested item 2ltligtltligtNested item 3ltligtltulgt ltl igt ltligtItem 3ltligtltulgt

      descendant $(ancestor descendant)

      Selects all elements that are descendants of a given ancestor

      Added in version 10

      $(ancestor descendant)

      ancestorSelector Any valid selector

      descendantSelector A selector to f ilter the descendant elements

      A descendant of an element could be a child grandchild great-grandchild and so on of thatelement

      Example 1 Finds all input descendants of forms

      Javascript

      $(form input)css(border 2px dotted blue)

      CSS

      body font-size14px form border2px green solid padding2px margin0 backgroundefe div colorred fieldset margin1px padding3px

      HTML

      ltformgt ltdivgtForm is surrounded by the green outl ineltdivgt ltlabelgtChildltlabelgt ltinput name=name gt

      ltfieldsetgt ltlabelgtGrandchildltlabelgt ltinput name=newsletter gt ltfieldsetgt

      ltformgt Sibling to form ltinput name=none gt

      multiple $(selector1 selector2 selectorN)

      Selects the combined results of all the specif ied selectors

      Added in version 10

      $(selector1 selector2 selectorN)

      selector1Selector Any valid selector

      selector2Selector Another valid selector

      selectorNSelector (opt ional) As many more valid selectors as you like

      You can specify any number of selectors to combine into a single result This mult ipleexpression combinator is an ef f icient way to select disparate elements The order of the DOMelements in the returned jQuery object may not be ident ical as they will be in document orderAn alternat ive to this combinator is the add() method

      Example 1 Finds the elements that match any of these three selectors

      Javascript

      $(divspanpmyClass)css(border3px solid red)

      HTML

      ltdivgtdivltdivgt

      ltp class=myClassgtp class=myClassltpgt ltp class=notMyClassgtp class=notMyClassltpgt ltspangtspanltspangt

      CSS

      divspanp width 126px height 60px floatleft padding 3px margin 2px background-color EEEEEE font-size14px

      Example 2 Show the order in the jQuery object

      Javascript

      var l ist = $(divpspan)map(function () return thistagName )get()join( ) $(b)append(documentcreateTextNode(list))

      CSS

      b colorred font-size16px displayblock clearleft divspanp width 40px height 40px floatleft margin 10px background-color blue padding3px colorwhite

      HTML

      ltspangtspanltspangt

      ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt ltspangtspanltspangt

      ltpgtpltpgt ltdivgtdivltdivgt ltbgtltbgt

      all $()

      Selects all elements

      Added in version 10

      $()

      Caut ion The all or universal selector is extremely slow except when used by itself

      Example 1 Finds every element (including head body etc) in the document

      Javascript

      var elementCount = $()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

      HTML

      ltdivgtDIVltdivgt

      ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgt

      CSS

      h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE

      Example 2 A common way to select all elements is to f ind within documentbody so elementslike head script etc are lef t out

      Javascript

      var elementCount = $(test)find()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

      HTML

      ltdiv id=testgt ltdivgtDIVltdivgt ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgtltdivgt

      CSS

      h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE test width auto height auto background-color transparent

      class $(class)

      Selects all elements with the given class

      Added in version 10

      $(class)

      classString A class to search for An element can have mult iple classes only one ofthem must match

      For class selectors jQuery uses JavaScript s nat ive getElementsByClassName() funct ion if thebrowser supports it

      Example 1 Finds the element with the class myClass

      Javascript

      $(myClass)css(border3px solid red)

      HTML

      ltdiv class=notMegtdiv class=notMeltdivgt

      ltdiv class=myClassgtdiv class=myClassltdivgt ltspan class=myClassgtspan class=myClassltspangt

      CSS

      divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

      Example 2 Finds the element with both myclass and otherclass classes

      Javascript

      $(myclassotherclass)css(border13px solid red)

      HTML

      ltdiv class=myclassgtdiv class=notMeltdivgt

      ltdiv class=myclass otherclassgtdiv class=myClassltdivgt ltspan class=myclass otherclassgtspan class=myClassltspangt

      CSS

      divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

      element $(element)

      Selects all elements with the given tag name

      Added in version 10

      $(element)

      elementString An element to search for Refers to the tagName of DOM nodes

      JavaScript s getElementsByTagName() funct ion is called to return the appropriate elementswhen this expression is used

      Example 1 Finds every DIV element

      Javascript

      $(div)css(border9px solid red)

      HTML

      ltdivgtDIV1ltdivgt

      ltdivgtDIV2ltdivgt ltspangtSPANltspangt

      CSS

      divspan width 60px height 60px floatleft padding 10px margin 10px background-color EEEEEE

      id $(id)

      Selects a single element with the given id at t ribute

      Added in version 10

      $( id)

      idString An ID to search for specif ied via the id at t ribute of an element

      For id selectors jQuery uses the JavaScript funct ion documentgetElementById() which isextremely ef f icient When another selector is at tached to the id selector such as h2pageTit lejQuery performs an addit ional check before ident ifying the element as a match

      As always remember that as a developer your time is typically the most valuableresource Do not focus on optimization of selector speed unless it is clear thatperformance needs to be improved

      Each id value must be used only once within a document If more than one element has beenassigned the same ID queries that use that ID will only select the f irst matched element in theDOM This behavior should not be relied on however a document with more than one elementusing the same ID is invalid

      If the id contains characters like periods or colons you have to escape those characters withbackslashes

      Example 1 Finds the element with the id myDiv

      Javascript

      $(myDiv)css(border3px solid red)

      HTML

      ltdiv id=notMegtltpgtid=notMeltpgtltdivgt

      ltdiv id=myDivgtid=myDivltdivgt

      CSS

      div width 90px height 90px floatleft padding 5px margin 5px background-color EEEEEE

      Example 2 Finds the element with the id myIDentry[1] See how certain characters must beescaped with backslashes

      Javascript

      $(myIDentry[1])css(border3px solid red)

      HTML

      ltdiv id=myIDentry[0]gtid=myIDentry[0]ltdivgt

      ltdiv id=myIDentry[1]gtid=myIDentry[1]ltdivgt ltdiv id=myIDentry[2]gtid=myIDentry[2]ltdivgt

      CSS

      div width 300px floatleft padding 2px margin 3px background-color EEEEEE

      Traversing

      has

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

      Added in version 14

      has(contained)jQuery

      containedElement A DOM element to match elements against

      Given a jQuery object that represents a set of DOM elements the has() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst the descendants of the matching elements the element will be included in the result ifany of its descendant elements matches the selector

      Consider a page with a nested list as follows

      ltulgt ltligtlist item 1ltligt ltligtlist item 2 ltulgt ltligtlist item 2-altligt ltligtlist item 2-bltligt ltulgt ltl igt ltligtlist item 3ltligt ltligtlist item 4ltligtltulgt

      We can apply this method to the set of list items as follows

      $( l i )has(ul )css(background-color red)

      The result of this call is a red background for item 2 as it is the only ltligt that has a ltulgt amongits descendants

      Example 1 Check if an element is inside another

      Javascript

      $(ul)append(ltligt + ($(ul)has(l i)length Yes No) + ltl igt) $(ul)has(l i)addClass(full)

      CSS

      ful l border 1px solid red

      HTML

      ltulgtltligtDoes the UL contain an LIltl igtltulgt

      parentsUntil

      Get the ancestors of each element in the current set of matched elements up to but notincluding the element matched by the selector DOM node or jQuery object

      Added in version 16

      parentsUnt il(element f ilter)jQuery

      elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching ancestor elements

      f ilterSelector (opt ional) A string containing a selector expression to matchelements against

      Given a selector expression that represents a set of DOM elements the parentsUnt il() methodtraverses through the ancestors of these elements unt il it reaches an element matched by theselector passed in the methods argument The result ing jQuery object contains all of theancestors up to but not including the one matched by the parentsUnt il() selector

      If the selector is not matched or is not supplied all ancestors will be selected in these cases itselects the same elements as the parents() method does when no selector is provided

      As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstparentsUnt il() argument

      The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

      Example 1 Find the ancestors of

      up to

      and give them a red background color Also f ind ancestors of

      that have a class of yes up toand give them a green border

      Javascript

      $(l i item-a)parentsUntil(level-1) css(background-color red)

      $(l i item-2)parentsUntil( $(ullevel-1) yes ) css(border 3px solid green)

      HTML

      ltul class=level-1 yesgt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2 yesgt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      prevUntil

      Get all preceding siblings of each element up to but not including the element matched by theselector DOM node or jQuery object

      Added in version 16

      prevUnt il(element f ilter)jQuery

      elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching preceding sibling elements

      f ilterSelector (opt ional) A string containing a selector expression to matchelements against

      Given a selector expression that represents a set of DOM elements the prevUnt il() methodsearches through the predecessors of these elements in the DOM tree stopping when itreaches an element matched by the methods argument The new jQuery object that isreturned contains all previous siblings up to but not including the one matched by theprevUnt il() selector the elements are returned in order f rom the closest sibling to the farthest

      If the selector is not matched or is not supplied all previous siblings will be selected in thesecases it selects the same elements as the prevAll() method does when no f ilter selector isprovided

      As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstprevUnt il() argument

      The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

      Example 1 Find the siblings that precede

      up to the precedingand give them a red background color Also f ind previous

      siblings ofup toand give them a green text color

      Javascript

      $(term-2)prevUntil(dt) css(background-color red) var term1 = documentgetElementById(term-1)$(term-3)prevUntil(term1 dd) css(color green)

      HTML

      ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

      ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

      ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

      nextUntil

      Get all following siblings of each element up to but not including the element matched by theselector DOM node or jQuery object passed

      Added in version 16

      nextUnt il(element f ilter)jQuery

      elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching following sibling elements

      f ilterSelector (opt ional) A string containing a selector expression to matchelements against

      Given a selector expression that represents a set of DOM elements the nextUnt il() methodsearches through the successors of these elements in the DOM tree stopping when it reachesan element matched by the methods argument The new jQuery object that is returnedcontains all following siblings up to but not including the one matched by the nextUnt il()argument

      If the selector is not matched or is not supplied all following siblings will be selected in thesecases it selects the same elements as the nextAll() method does when no f ilter selector isprovided

      As of jQuery 16 A DOM node or jQuery object instead of a selector may be passed to thenextUnt il() method

      The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

      Example 1 Find the siblings that follow

      up to the nextand give them a red background color Also f ind

      siblings that followup toand give them a green text color

      Javascript

      $(term-2)nextUntil(dt) css(background-color red)

      var term3 = documentgetElementById(term-3)$(term-1)nextUntil(term3 dd) css(color green)

      HTML

      ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

      ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

      ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

      each

      Iterate over a jQuery object execut ing a funct ion for each matched element

      Added in version 10

      each(funct ion(index Element))jQuery

      funct ion(index Element)Funct ion A funct ion to execute for each matched element

      The each() method is designed to make DOM looping constructs concise and less error-proneWhen called it iterates over the DOM elements that are part of the jQuery object Each t ime thecallback runs it is passed the current loop iterat ion beginning from 0 More important ly thecallback is f ired in the context of the current DOM element so the keyword this refers to theelement

      Suppose we had a simple unordered list on the page

      ltulgt ltligtfooltligt ltligtbarltligt ltulgt

      We can select the list items and iterate across them

      $( l i )each(function(index) alert(index + + $(this)text()) )

      A message is thus alerted for each item in the list

      0 foo

      1 bar

      We can stop the loop from within the callback funct ion by returning false

      Example 1 Iterates over three divs and sets their color property

      Javascript

      $(documentbody)cl ick(function () $(div)each(function (i) i f (thisstylecolor = blue) thisstylecolor = blue else thisstylecolor = ) )

      CSS

      div colorred text-aligncenter cursorpointer font-weightbolder width300px

      HTML

      ltdivgtClick hereltdivgt

      ltdivgtto iterate throughltdivgt ltdivgtthese divsltdivgt

      Example 2 If you want to have the jQuery object instead of the regular DOM element use the$(this) funct ion for example

      Javascript

      $(span)cl ick(function () $(l i)each(function() $(this)toggleClass(example) ) )

      CSS

      ul font-size18px margin0 span colorblue text-decorationunderline cursorpointer example font-styleital ic

      HTML

      To do l ist ltspangt(click here to change)ltspangt ltulgt ltligtEatltligt ltligtSleepltligt

      ltligtBe merryltligt ltulgt

      Example 3 You can use return to break out of each() loops early

      Javascript

      $(button)cl ick(function () $(div)each(function (index domEle) domEle == this $(domEle)css(backgroundColor yellow) i f ($(this)is(stop)) $(span)text(Stopped at div index + index) return false ) )

      CSS

      div width40px height40px margin5px floatleft border2px blue solid text-aligncenter span colorred

      HTML

      ltbuttongtChange colorsltbuttongt ltspangtltspangt ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdiv id=stopgtStop hereltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt

      first

      Reduce the set of matched elements to the f irst in the set

      Added in version 14

      f irst()jQuery

      [

      Given a jQuery object that represents a set of DOM elements the f irst() method constructs anew jQuery object f rom the f irst matching element

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      We can apply this method to the set of list items

      $( l i )first()css(background-color red)

      The result of this call is a red background for the f irst item

      Example 1 Highlight the f irst span in a paragraph

      CSS

      highlightbackground-color yellow

      Javascript

      $(p span)first()addClass(highlight)

      HTML

      ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

      last

      Reduce the set of matched elements to the f inal one in the set

      Added in version 14

      last()jQuery

      [

      Given a jQuery object that represents a set of DOM elements the last() method constructs anew jQuery object f rom the last matching element

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      We can apply this method to the set of list items

      $( l i )last()css(background-color red)

      The result of this call is a red background for the f inal item

      Example 1 Highlight the last span in a paragraph

      CSS

      highlightbackground-color yellow

      Javascript

      $(p span)last()addClass(highlight)

      HTML

      ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

      slice

      Reduce the set of matched elements to a subset specif ied by a range of indices

      Added in version 114

      slice(start end)jQuery

      start Integer An integer indicat ing the 0-based posit ion at which the elements begin tobe selected If negat ive it indicates an of fset f rom the end of the set

      endInteger (opt ional) An integer indicat ing the 0-based posit ion at which theelements stop being selected If negat ive it indicates an of fset f rom theend of the set If omit ted the range cont inues unt il the end of the set

      Given a jQuery object that represents a set of DOM elements the slice() method constructs anew jQuery object f rom a subset of the matching elements The supplied start index ident if iesthe posit ion of one of the elements in the set if end is omit ted all elements af ter this one willbe included in the result

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      We can apply this method to the set of list items

      $( l i )sl ice(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 iszero-based and refers to the posit ion of elements within the jQuery object not within theDOM tree

      The end parameter allows us to limit the selected range even further For example

      $( l i )sl ice(2 4)css(background-color red)

      Now only items 3 and 4 are selected The index is once again zero-based the range extends upto but not including the specif ied index

      Negative Indices

      The jQuery slice() method is patterned af ter the JavaScript slice() method for arrays One ofthe features that it mimics is the ability for negat ive numbers to be passed as either the start orend parameter If a negat ive number is provided this indicates a posit ion start ing f rom the endof the set rather than the beginning For example

      $( l i )sl ice(-2 -1)css(background-color red)

      This t ime only list item 4 is turned red since it is the only item in the range between two fromthe end (-2) and one from the end (-1)

      Example 1 Turns divs yellow based on a random slice

      Javascript

      function colorEm() var $div = $(div) var start = Mathfloor(Mathrandom() $divlength) var end = Mathfloor(Mathrandom() ($divlength - start)) + start + 1 i f (end == $divlength) end = undefined $divcss(background ) i f (end) $divsl ice(start end)css(background yellow) else $divsl ice(start)css(background yellow) $(span)text($(div)sl ice( + start + (end + end ) + )css(background yellow))

      $(button)cl ick(colorEm)

      CSS

      div width40px height40px margin10px floatleft border2px solid blue span colorred font-weightbold button margin5px

      HTML

      ltpgtltbuttongtTurn sl ice yellowltbuttongt ltspangtClick the buttonltspangtltpgt ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt

      Example 2 Selects all paragraphs then slices the select ion to include only the f irst element

      Javascript

      $(p)sl ice(0 1)wrapInner(ltbgtltbgt)

      Example 3 Selects all paragraphs then slices the select ion to include only the f irst and secondelement

      Javascript

      $(p)sl ice(0 2)wrapInner(ltbgtltbgt)

      Example 4 Selects all paragraphs then slices the select ion to include only the second element

      Javascript

      $(p)sl ice(1 2)wrapInner(ltbgtltbgt)

      Example 5 Selects all paragraphs then slices the select ion to include only the second and thirdelement

      Javascript

      $(p)sl ice(1)wrapInner(ltbgtltbgt)

      Example 6 Selects all paragraphs then slices the select ion to include only the third element

      Javascript

      $(p)sl ice(-1)wrapInner(ltbgtltbgt)

      end

      End the most recent f iltering operat ion in the current chain and return the set of matchedelements to its previous state

      Added in version 10

      end()jQuery

      Most of jQuerys DOM traversal methods operate on a jQuery object instance and produce anew one matching a dif ferent set of DOM elements When this happens it is as if the new setof elements is pushed onto a stack that is maintained inside the object Each successivef iltering method pushes a new element set onto the stack If we need an older element set wecan use end() to pop the sets back of f of the stack

      Suppose we have a couple short lists on a page

      ltul class=firstgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgtltul class=secondgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgt

      The end() method is useful primarily when exploit ing jQuerys chaining propert ies When notusing chaining we can usually just call up a previous object by variable name so we dont needto manipulate the stack With end() though we can string all the method calls together

      $(ulfirst)find(foo)css(background-color red) end()find(bar)css(background-color green)

      This chain searches for items with the class foo within the f irst list only and turns theirbackgrounds red Then end() returns the object to its state before the call to f ind() so thesecond f ind() looks for bar inside ltul class=f irstgt not just inside that list s ltli class=foogtand turns the matching elements backgrounds green The net result is that items 1 and 3 ofthe f irst 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 f iltering methodsproviding the openings of nested blocks and end() methods closing them

      $(ulfirst)find(foo) css(background-color red)end()find(bar) css(background-color green)end()

      The last end() is unnecessary as we are discarding the jQuery object immediately thereafterHowever when the code is writ ten in this form the end() provides visual symmetry and a senseof complet ion acirceurordquomaking the program at least to the eyes of some developers more readableat the cost of a slight hit to performance as it is an addit ional funct ion call

      Example 1 Selects all paragraphs f inds span elements inside these and reverts the select ionback to the paragraphs

      Javascript

      jQueryfnshowTags = function (n) var tags = thismap(function () return thistagName ) get()join( ) $(beq( + n + ))text(tags) return this

      $(p)showTags(0) find(span) showTags(1) css(background yellow) end() showTags(2) css(font-style ital ic)

      CSS

      p div margin1px padding1px font-weightbold font-size16px div colorblue b colorred

      HTML

      ltpgt Hi there ltspangthowltspangt are you ltspangtdoingltspangt ltpgt

      ltpgt This ltspangtspanltspangt is one of several ltspangtspansltspangt in this ltspangtsentenceltspangt ltpgt

      ltdivgt Tags in jQuery object initial ly ltbgtltbgt ltdivgt ltdivgt Tags in jQuery object after find ltbgtltbgt

      ltdivgt ltdivgt Tags in jQuery object after end ltbgtltbgt ltdivgt

      Example 2 Selects all paragraphs f inds span elements inside these and reverts the select ion

      back to the paragraphs

      Javascript

      $(p)find(span)end()css(border 2px red solid)

      CSS

      p margin10px padding10px

      HTML

      ltpgtltspangtHelloltspangt how are youltpgt

      andSelf

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

      Added in version 12

      andSelf()jQuery

      As described in the discussion for end() jQuery objects maintain an internal stack that keepstrack of changes to the matched set of elements When one of the DOM traversal methods iscalled the new set of elements is pushed onto the stack If the previous set of elements isdesired as well andSelf() can help

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      The result of the following code is a red background behind items 3 4 and 5

      $( l i third-item)nextAll()andSelf() css(background-color red)

      First the init ial selector locates item 3 init ializing the stack with the set containing just this itemThe call to nextAll() then pushes the set of items 4 and 5 onto the stack Finally the andSelf()invocat ion merges these two sets together creat ing a jQuery object that points to all three

      items in document order [ltlithird-itemgtltligtltligt ]

      Example 1 Find all divs and all the paragraphs inside of them and give them both class namesNot ice the div doesnt have the yellow background color since it didnt use andSelf()

      Javascript

      $(div)find(p)andSelf()addClass(border) $(div)find(p)addClass(background)

      CSS

      p div margin5px padding5px border border 2px solid red background backgroundyellow

      HTML

      ltdivgt ltpgtFirst Paragraphltpgt ltpgtSecond Paragraphltpgt ltdivgt

      siblings

      Get the siblings of each element in the set of matched elements opt ionally f iltered by aselector

      Added in version 10

      siblings(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the siblings() method allows usto search through the siblings of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      If we begin at the third item we can f ind its siblings

      $( l i 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 aselector expression all of the siblings are part of the object If we had supplied one only thematching items among these four would be included

      The original element is not included among the siblings which is important to remember whenwe wish to f ind all elements at a part icular level of the DOM tree

      Example 1 Find the unique siblings of all yellow li elements in the 3 lists (including other yellow lielements if appropriate)

      Javascript

      var len = $(hil ite)siblings() css(color red) length $(b)text(len)

      CSS

      ul floatleft margin5px font-size16px font-weightbold p colorblue margin10px 20px font-size16px padding5px font-weightbolder hi l ite backgroundyellow

      HTML

      ltulgt ltligtOneltligt

      ltligtTwoltligt ltli class=hil itegtThreeltligt ltligtFourltligt ltulgt

      ltulgt ltligtFiveltligt ltligtSixltligt ltligtSevenltligt

      ltulgt ltulgt ltligtEightltligt ltli class=hil itegtNineltligt

      ltligtTenltligt ltli class=hil itegtElevenltligt ltulgt ltpgtUnique siblings ltbgtltbgtltpgt

      Example 2 Find all siblings with a class selected of each div

      Javascript

      $(p)siblings(selected)css(background yellow)

      HTML

      ltdivgtltspangtHelloltspangtltdivgt

      ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

      prevAll

      Get all preceding siblings of each element in the set of matched elements opt ionally f iltered bya selector

      Added in version 12

      prevAll(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the prevAll() method searchesthrough the predecessors of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements the elements are returned in order beginning with theclosest sibling

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      If we begin at the third item we can f ind the elements which come before it

      $( l i 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 aselector 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

      Example 1 Locate all the divs preceding the last div and give them a class

      Javascript

      $(divlast)prevAll()addClass(before)

      CSS

      div width70px height70px backgroundabc border2px solid black margin10px floatleft divbefore border-color red

      HTML

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      prev

      Get the immediately preceding sibling of each element in the set of matched elementsopt ionally f iltered by a selector

      Added in version 10

      prev(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the prev() method allows us tosearch through the predecessors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      If we begin at the third item we can f ind the element which comes just before it

      $( l i 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 selectorexpression this preceding element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

      Example 1 Find the very previous sibling of each div

      Javascript

      var $curr = $(start) $currcss(background f99) $(button)cl ick(function () $curr = $currprev() $(div)css(background ) $currcss(background f99) )

      CSS

      div width40px height40px margin10px floatleft border2px blue solid padding2px span font-size14px p clearleft margin10px

      HTML

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltspangthas childltspangtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdiv id=startgtltdivgt

      ltdivgtltdivgt ltpgtltbuttongtGo to Prevltbuttongtltpgt

      Example 2 For each paragraph f ind the very previous sibling that has a class selected

      Javascript

      $(p)prev(selected)css(background yellow)

      HTML

      ltdivgtltspangtHelloltspangtltdivgt

      ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

      parents

      Get the ancestors of each element in the current set of matched elements opt ionally f iltered

      by a selector

      Added in version 10

      parents(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the parents() method allows usto search through the ancestors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements ordered from immediate parent on up the elementsare returned in order f rom the closest parent to the outer ones The parents() and parent()methods are similar except that the lat ter only t ravels a single level up the DOM tree

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a basic nested list on it

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      If we begin at item A we can f ind its ancestors

      $( l i 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 onup the DOM tree all the way to the lthtmlgt element) Since we do not supply a selectorexpression 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

      Example 1 Find all parent elements of each b

      Javascript

      var parentEls = $(b)parents() map(function () return thistagName ) get()join( )$(b)append(ltstronggt + parentEls + ltstronggt)

      CSS

      b span p html body padding 5em border 1px solid b colorblue strong colorred

      HTML

      ltdivgt ltpgt ltspangt ltbgtMy parents are ltbgt ltspangt

      ltpgt ltdivgt

      Example 2 Click to f ind all unique div parent elements of each span

      Javascript

      function showParents() $(div)css(border-color white) var len = $(spanselected) parents(div) css(border 2px red solid) length $(b)text(Unique div parents + len)$(span)cl ick(function () $(this)toggleClass(selected) showParents())

      CSS

      p div span margin2px padding1px div border2px white solid span cursorpointer font-size12px selected colorblue b colorred displayblock font-size14px

      HTML

      ltpgt ltdivgt ltdivgtltspangtHelloltspangtltdivgt ltspangtHello Againltspangt

      ltdivgt ltdivgt ltspangtAnd Hello Againltspangt ltdivgt ltpgt

      ltbgtClick Hellos to toggle their parentsltbgt

      parent

      Get the parent of each element in the current set of matched elements opt ionally f iltered by aselector

      Added in version 10

      parent(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the parent() method allows usto search through the parents of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements The parents() and parent() methods are similar exceptthat the lat ter only t ravels a single level up the DOM tree

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a basic nested list on it

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      If we begin at item A we can f ind its parents

      $( l i 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 selectorexpression the parent element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

      Example 1 Shows the parent of each element as (parent gt child) Check the View Source tosee the raw html

      Javascript

      $( documentbody)each(function () var parentTag = $(this)parent()get(0)tagName $(this)prepend(documentcreateTextNode(parentTag + gt )) )

      CSS

      divp margin10px

      HTML

      ltdivgtdiv ltspangtspan ltspangt ltbgtb ltbgt

      ltdivgt ltpgtp ltspangtspan ltemgtem ltemgt ltspangt ltpgt

      ltdivgtdiv ltstronggtstrong ltspangtspan ltspangt ltemgtem ltbgtb ltbgt ltemgt

      ltstronggt ltbgtb ltbgt ltdivgt

      Example 2 Find the parent element of each paragraph with a class selected

      Javascript

      $(p)parent(selected)css(background yellow)

      HTML

      ltdivgtltpgtHelloltpgtltdivgt

      ltdiv class=selectedgtltpgtHello Againltpgtltdivgt

      offsetParent

      Get the closest ancestor element that is posit ioned

      Added in version 126

      offsetParent()jQuery

      Given a jQuery object that represents a set of DOM elements the of fsetParent() methodallows us to search through the ancestors of these elements in the DOM tree and construct anew jQuery object wrapped around the closest posit ioned ancestor An element is said to beposit ioned if it has a CSS posit ion at t ribute of relat ive absolute or f ixed This informat ion isuseful for calculat ing of fsets for performing animat ions and placing objects on the page

      Consider a page with a basic nested list on it with a posit ioned element

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      If we begin at item A we can f ind its posit ioned ancestor

      $( l i item-a)offsetParent()css(background-color red)

      This will change the color of list item II which is posit ioned

      Example 1 Find the of fsetParent of item A

      Javascript

      $( l i item-a)offsetParent()css(background-color red)

      HTML

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igt ltulgt

      nextAll

      Get all following siblings of each element in the set of matched elements opt ionally f iltered bya selector

      Added in version 12

      nextAll(selector)jQuery

      selectorString (opt ional) A string containing a selector expression to match elementsagainst

      Given a jQuery object that represents a set of DOM elements the nextAll() method allows usto search through the successors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      If we begin at the third item we can f ind the elements which come after it

      $( l i 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 aselector 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

      Example 1 Locate all the divs af ter the f irst and give them a class

      Javascript

      $(divfirst)nextAll()addClass(after)

      CSS

      div width 80px height 80px background abc border 2px solid black margin 10px float left divafter border-color red

      HTML

      ltdivgtfirstltdivgt ltdivgtsiblingltdivgtchildltdivgtltdivgt ltdivgtsiblingltdivgt

      ltdivgtsiblingltdivgt

      Example 2 Locate all the paragraphs af ter the second child in the body and give them a class

      Javascript

      $(nth-child(1))nextAll(p)addClass(after)

      CSS

      div p width 60px height 60px background abc border 2px solid black margin 10px float left after border-color red

      HTML

      ltpgtpltpgt

      ltdivgtdivltdivgt ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt

      ltpgtpltpgt ltdivgtdivltdivgt

      next

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

      Added in version 10

      next(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the next() method allows us tosearch through the immediately following sibling of these elements in the DOM tree andconstruct a new jQuery object f rom the matching elements

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the immediately following sibling matches the selector it remains in the newlyconstructed jQuery object otherwise it is excluded

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      If we begin at the third item we can f ind the element which comes just af ter it

      $( l i 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 hadsupplied one the element would be tested for a match before it was included

      Example 1 Find the very next sibling of each disabled button and change its text this button isdisabled

      Javascript

      $(button[disabled])next()text(this button is disabled)

      CSS

      span colorblue font-weightbold button width100px

      HTML

      ltdivgtltbutton disabled=disabledgtFirstltbuttongt - ltspangtltspangtltdivgt ltdivgtltbuttongtSecondltbuttongt - ltspangtltspangtltdivgt

      ltdivgtltbutton disabled=disabledgtThirdltbuttongt - ltspangtltspangtltdivgt

      Example 2 Find the very next sibling of each paragraph Keep only the ones with a classselected

      Javascript

      $(p)next(selected)css(background yellow)

      HTML

      ltpgtHelloltpgt

      ltp class=selectedgtHello Againltpgt ltdivgtltspangtAnd Againltspangtltdivgt

      find

      Get the descendants of each element in the current set of matched elements f iltered by aselector jQuery object or element

      Added in version 16

      f ind(element)jQuery

      elementElement An element to match elements against

      Given a jQuery object that represents a set of DOM elements the f ind() method allows us tosearch through the descendants of these elements in the DOM tree and construct a newjQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree

      The f irst signature for the f ind()method accepts a selector expression of the same type thatwe can pass to the $() funct ion The elements will be f iltered by test ing whether they match thisselector

      Consider a page with a basic nested list on it

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      If we begin at item II we can f ind list items within it

      $( l i item-ii )find( l i )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 IImatches the selector expression it is not included in the results only descendants areconsidered candidates for the match

      Unlike in the rest of the tree traversal methods the selector expression is requiredin a call to find() If we need to retrieve all of the descendant elements we canpass in the universal selector to accomplish this

      Selector context is implemented with the f ind() method therefore $(liitem-ii)f ind(li) isequivalent to $(li liitem-ii)

      As of jQuery 16 we can also f ilter the select ion with a given jQuery collect ion or element Withthe same nested list as above if we start with

      var $allListElements = $( l i )

      And then pass this jQuery object to f ind

      $( l i item-ii )find( $allListElements )

      This will return a jQuery collect ion which contains only the list elements that are descendantsof item II

      Similarly an element may also be passed to f ind

      var item1 = $( l i item-1)[0]$( l i item-ii )find( item1 )css(background-color red)

      The result of this call would be a red background on item 1

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

      Javascript

      $(p)find(span)css(color red)

      HTML

      ltpgtltspangtHelloltspangt how are youltpgtltpgtMe Im ltspangtgoodltspangtltpgt

      Example 2 A select ion using a jQuery collect ion of all span tags Only spans within p tags arechanged to red while others are lef t blue

      CSS

      span color blue

      Javascript

      var $spans = $(span) $(p)find( $spans )css(color red)

      HTML

      ltpgtltspangtHelloltspangt how are youltpgt ltpgtMe Im ltspangtgoodltspangtltpgt ltdivgtDid you ltspangteatltspangt yetltdivgt

      Example 3 Add spans around each word then add a hover and italicize words with the let ter t

      Javascript

      var newText = $(p)text()split( )join(ltspangt ltspangt) newText = ltspangt + newText + ltspangt

      $(p)html( newText ) find(span) hover(function() $(this)addClass(hil ite) function() $(this)removeClass(hil ite) ) end() find(contains(t)) css(font-style ital ic font-weightbolder)

      CSS

      p font-size20px width200px cursordefault colorblue font-weightbold margin0 10px hi l ite backgroundyellow

      HTML

      ltpgt When the day is short find that which matters to you or stop believing ltpgt

      contents

      Get the children of each element in the set of matched elements including text and commentnodes

      Added in version 12

      contents()jQuery

      Given a jQuery object that represents a set of DOM elements the contents() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The contents() and children() methods aresimilar except that the former includes text nodes as well as HTML elements in the result ingjQuery object

      The contents() method can also be used to get the content document of an if rame if theif rame is on the same domain as the main page

      Consider a simple ltdivgt with a number of text nodes each of which is separated by two linebreak elements (ltbr gt)

      ltdiv class=containergt Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ltbr gtltbr gt Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut al iquip ex ea commodo consequat ltbr gt ltbr gt Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariaturltdivgt

      We can employ the contents() method to help convert this blob of text into three well-formedparagraphs

      $(container)contents()fi lter(function() return thisnodeType == 3) wrap(ltpgtltpgt)end()fi lter(br) remove()

      This code f irst retrieves the contents of ltdiv class=containergt and then f ilters it for textnodes which are wrapped in paragraph tags This is accomplished by test ing the nodeTypeproperty of the element This DOM property holds a numeric code indicat ing the nodes typetext nodes use the code 3 The contents are again f iltered this t ime for ltbr gt elements andthese elements are removed

      Example 1 Find all the text nodes inside a paragraph and wrap them with a bold tag

      Javascript

      $(p)contents()fi lter(function() return thisnodeType = 1 )wrap(ltbgt)

      HTML

      ltpgtHello lta href=httpejohnorggtJohnltagt how are you doingltpgt

      Example 2 Change the background colour of links inside of an if rame

      Javascript

      $(frameDemo)contents()find(a)css(background-colorBADA55)

      HTML

      ltiframe src=httpapijquerycom width=80 height=600 id=frameDemogtltiframegt

      closest

      Get the f irst ancestor element that matches the selector beginning at the current element andprogressing up through the DOM tree

      Added in version 16

      closest(element)jQuery

      elementElement An element to match elements against

      Given a jQuery object that represents a set of DOM elements the closest() method allows usto search through these elements and their ancestors in the DOM tree and construct a newjQuery object f rom the matching elements The parents() and closest() methods are similar inthat they both t raverse up the DOM tree The dif ferences between the two though subt le aresignif icant

      closest() parents()

      Begins with thecurrent element

      Begins with the parent element

      Travels up the DOMtree unt il it f inds amatch for the suppliedselector

      Travels up the DOM tree to the document s root elementadding each ancestor element to a temporary collect ion it thenf ilters that collect ion based on a selector if one is supplied

      The returned jQueryobject contains zeroor one element

      The returned jQuery object contains zero one or mult ipleelements

      ltul id=one class=level-1gt ltli class=item-igtIltl igt ltli id=ii class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      Suppose we perform a search for ltulgt elements start ing at item A

      $( l i item-a)closest(ul ) css(background-color red)

      This will change the color of the level-2 ltulgt since it is the f irst encountered when traveling upthe DOM tree

      Suppose we search for an ltligt element instead

      $( l i item-a)closest( l i ) css(background-color red)

      This will change the color of list item A The closest() method begins its search with theelement itself before progressing up the DOM tree and stops when item A matches theselector

      We can pass in a DOM element as the context within which to search for the closest element

      var l istItemII = documentgetElementById( i i )$( l i item-a)closest(ul l istItemII) css(background-color red)$( l i item-a)closest(one l istItemII) css(background-color green)

      This will change the color of the level-2 ltulgt because it is both the f irst ltulgt ancestor of listitem A and a descendant of list item II It will not change the color of the level-1 ltulgt howeverbecause it is not a descendant of list item II

      Example 1 Show how event delegat ion can be done with closest The closest list elementtoggles a yellow background when it or its descendent is clicked

      Javascript

      $( document )bind(click function( e ) $( etarget )closest(l i)toggleClass(hil ight) )

      CSS

      l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

      HTML

      ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

      Example 2 Pass a jQuery object to closest The closest list element toggles a yellowbackground when it or its descendent is clicked

      Javascript

      var $listElements = $(l i)css(color blue) $( document )bind(click function( e ) $( etarget )closest( $listElements )toggleClass(hil ight) )

      CSS

      l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

      HTML

      ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

      closest

      Gets an array of all the elements and selectors matched against the current element upthrough the DOM tree

      Added in version 14

      closest(selectors context)Array

      selectorsArray An array or string containing a selector expression to match elementsagainst (can also be a jQuery object)

      context Element (opt ional) A DOM element within which a matching element may befound If no context is passed in then the context of the jQuery setwill be used instead

      This method is primarily meant to be used internally or by plugin authors

      Example 1 Show how event delegat ion can be done with closest

      Javascript

      var close = $(l i first)closest([ul body]) $each(close function(i) $(l i)eq(i)html( thisselector + + thiselemnodeName ) )

      CSS

      HTML

      ltulgtltligtltligtltligtltligtltulgt

      children

      Get the children of each element in the set of matched elements opt ionally f iltered by aselector

      Added in version 10

      children(selector)jQuery

      selectorSelector (opt ional) A string containing a selector expression to matchelements against

      Given a jQuery object that represents a set of DOM elements the children() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree Note also that like mostjQuery methods children() does not return text nodes to get all children including text andcomment nodes use contents()

      The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

      Consider a page with a basic nested list on it

      ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

      If we begin at the level-2 list we can f ind its children

      $(ullevel-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 aselector expression all of the children are part of the returned jQuery object If we had suppliedone only the matching items among these three would be included

      Example 1 Find all children of the clicked element

      Javascript

      $(container)cl ick(function (e) $()removeClass(hil ite) var $kids = $(etarget)children() var len = $kidsaddClass(hil ite)length

      $(results spanfirst)text(len) $(results spanlast)text(etargettagName)

      epreventDefault() return false )

      CSS

      body font-size16px font-weightbolder div width130px height82px margin10px floatleft border1px solid blue padding4px container widthauto height105px margin0 floatnone bordernone hi l ite border-colorred results displayblock colorred p margin10px border1px solid transparent span colorblue border1px solid transparent input width100px em border1px solid transparent a border1px solid transparent b border1px solid transparent button border1px solid transparent

      HTML

      ltdiv id=containergt

      ltdivgt ltpgtThis ltspangtis the ltemgtwayltemgt weltspangt write ltemgttheltemgt demoltpgt

      ltdivgt ltdivgt lta href=gtltbgtwltbgtritltbgteltbgtltagt the ltspangtdemoltspangt ltbuttongtwrite theltbuttongt demo ltdivgt

      ltdivgt This ltspangtthe way we ltemgtwriteltemgt the ltemgtdemoltemgt soltspangt

      ltinput type=text value=early gt in ltdivgt ltpgt ltspangttltspangthe ltspangtmltspangtorning ltspan id=resultsgtFound ltspangt0ltspangt children in ltspangtTAGltspangtltspangt

      ltpgt ltdivgt

      Example 2 Find all children of each div

      Javascript

      $(div)children()css(border-bottom 3px double red)

      CSS

      body font-size16px font-weightbolder span colorblue p margin5px 0

      HTML

      ltpgtHello (this is a paragraph)ltpgt

      ltdivgtltspangtHello Again (this span is a child of the a div)ltspangtltdivgt ltpgtAnd ltspangtAgainltspangt (in another paragraph)ltpgt

      ltdivgtAnd One Last ltspangtTimeltspangt (most text directly in a div)ltdivgt

      Example 3 Find all children with a class selected of each div

      Javascript

      $(div)children(selected)css(color blue)

      CSS

      body font-size16px font-weightbolder p margin5px 0

      HTML

      ltdivgt ltspangtHelloltspangt ltp class=selectedgtHello Againltpgt ltdiv class=selectedgtAnd Againltdivgt

      ltpgtAnd One Last Timeltpgt ltdivgt

      add

      Add elements to the set of matched elements

      Added in version 14

      add(selector context)jQuery

      selectorSelector A string represent ing a selector expression to f ind addit ionalelements to add to the set of matched elements

      context Element The point in the document at which the selector should beginmatching similar to the context argument of the $(selector context)method

      Given a jQuery object that represents a set of DOM elements the add() method constructs anew jQuery object f rom the union of those elements and the ones passed into the methodThe argument to add() can be pret ty much anything that $() accepts including a jQueryselector 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 avariable for later use For example

      $(p)add(div)addClass(widget)var pdiv = $(p)add(div)

      The following will not save the added elements because the add() method creates a new setand leaves the original set in pdiv unchanged

      var pdiv = $(p)pdivadd(div) WRONG pdiv wil l not change

      Consider a page with a simple list and a paragraph following it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligtltulgtltpgta paragraphltpgt

      We can select the list items and then the paragraph by using either a selector or a reference tothe DOM element itself as the add() methods argument

      $( l i )add(p)css(background-color red)

      Or

      $( l i )add(documentgetElementsByTagName(p)[0]) css(background-color red)

      The result of this call is a red background behind all four elements Using an HTML snippet asthe add() methods argument (as in the third version) we can create addit ional elements on thef ly and add those elements to the matched set of elements Let s say for example that wewant to alter the background of the list items along with a newly created paragraph

      $( l i )add(ltp id=newgtnew paragraphltpgt) css(background-color red)

      Although the new paragraph has been created and its background color changed it st ill doesnot appear on the page To place it on the page we could add one of the insert ion methods tothe chain

      As of jQuery 14 the results f rom add() will always be returned in document order (rather than asimple concatenat ion)

      Note To reverse the add() you can use not( elements | selector ) to remove elements f rom thejQuery results or end() to return to the select ion before you added

      Example 1 Finds all divs and makes a border Then adds all paragraphs to the jQuery object toset their backgrounds yellow

      Javascript

      $(div)css(border 2px solid red) add(p) css(background yellow)

      CSS

      div width60px height60px margin10px floatleft p clearleft font-weightbold font-size16px colorblue margin0 10px padding2px

      HTML

      ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      ltpgtAdded this (notice no border)ltpgt

      Example 2 Adds more elements matched by the given expression to the set of matchedelements

      Javascript

      $(p)add(span)css(background yellow)

      HTML

      ltpgtHelloltpgtltspangtHello Againltspangt

      Example 3 Adds more elements created on the f ly to the set of matched elements

      Javascript

      $(p)clone()add(ltspangtAgainltspangt)appendTo(documentbody)

      HTML

      ltpgtHelloltpgt

      Example 4 Adds one or more Elements to the set of matched elements

      Javascript

      $(p)add(documentgetElementById(a))css(background yellow)

      HTML

      ltpgtHelloltpgtltspan id=agtHello Againltspangt

      Example 5 Demonstrates how to add (or push) elements to an exist ing collect ion

      Javascript

      var collection = $(p) capture the new collectioncollection = collectionadd(documentgetElementById(a))collectioncss(background yellow)

      HTML

      ltpgtHelloltpgtltspan id=agtHello Againltspangt

      not

      Remove elements f rom the set of matched elements

      Added in version 14

      not(funct ion(index))jQuery

      funct ion(index)Funct ion A funct ion used as a test for each element in the set this isthe current DOM element

      Given a jQuery object that represents a set of DOM elements the not() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element the elements that dont match the selector will be included in the result

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      We can apply this method to the set of list items

      $( l i )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 not() method allows us to remove elements f rom the matched setassuming we have found those elements previously by some other means For examplesuppose our list had an id applied to one of its items

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli id=notligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      We can fetch the third list item using the nat ive JavaScript getElementById() funct ion thenremove it f rom a jQuery object

      $( l i )not(documentgetElementById(notl i )) css(background-color red)

      This statement changes the color of items 1 2 4 and 5 We could have accomplished thesame thing with a simpler jQuery expression but this technique can be useful when forexample other libraries provide references to plain DOM nodes

      As of jQuery 14 the not() method can take a funct ion as its argument in the same way thatf ilter() does Elements for which the funct ion returns t rue are excluded from the f iltered set allother elements are included

      Example 1 Adds a border to divs that are not green or blue

      Javascript

      $(div)not(green blueone) css(border-color red)

      CSS

      div width50px height50px margin10px floatleft backgroundyellow border2px solid white green background8f8 gray backgroundccc blueone background99f

      HTML

      ltdivgtltdivgt ltdiv id=blueonegtltdivgt ltdivgtltdivgt ltdiv class=greengtltdivgt

      ltdiv class=greengtltdivgt ltdiv class=graygtltdivgt ltdivgtltdivgt

      Example 2 Removes the element with the ID selected f rom the set of all paragraphs

      Javascript

      $(p)not( $(selected)[0] )

      Example 3 Removes the element with the ID selected f rom the set of all paragraphs

      Javascript

      $(p)not(selected)

      Example 4 Removes all elements that match div pselected f rom the total set of allparagraphs

      Javascript

      $(p)not($(div pselected))

      map

      Pass each element in the current matched set through a funct ion producing a new jQueryobject containing the return values

      Added in version 12

      map(callback(index domElement))jQuery

      callback(indexdomElement)Funct ion

      A funct ion object that will be invoked for each element inthe current set

      As the return value is a jQuery-wrapped array it s very common to get() the returned object towork with a basic array

      The map() method is part icularly useful for gett ing or set t ing the value of a collect ion ofelements Consider a form with a set of checkboxes in it

      ltform method=post action=gt ltfieldsetgt ltdivgt ltlabel for=twogt2ltlabelgt ltinput type=checkbox value=2 id=two name=number[]gt ltdivgt ltdivgt ltlabel for=fourgt4ltlabelgt ltinput type=checkbox value=4 id=four name=number[]gt ltdivgt ltdivgt ltlabel for=sixgt6ltlabelgt ltinput type=checkbox value=6 id=six name=number[]gt ltdivgt ltdivgt ltlabel for=eightgt8ltlabelgt ltinput type=checkbox value=8 id=eight name=number[]gt ltdivgt ltfieldsetgtltformgt

      We can get a comma-separated list of checkbox IDs

      $(checkbox)map(function() return thisid)get()join( )

      The result of this call is the string twofoursixeight

      Within the callback funct ion this refers to the current DOM element for each iterat ion Thefunct ion can return an individual data item or an array of data items to be inserted into theresult ing set If an array is returned the elements inside the array are inserted into the set If thefunct ion returns null or undef ined no element will be inserted

      Example 1 Build a list of all the values within a form

      Javascript

      $(p)append( $(input)map(function() return $(this)val() )get()join( ) )

      CSS

      p colorred

      HTML

      ltpgtltbgtValues ltbgtltpgt ltformgt ltinput type=text name=name value=Johngt

      ltinput type=text name=password value=passwordgt ltinput type=text name=url value=httpejohnorggt

      ltformgt

      Example 2 A contrived example to show some funct ionality

      Javascript

      var mappedItems = $(l i)map(function (index) var replacement = $(ltligt)text($(this)text())get(0) i f (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$(ltligt)get(0)] $(replacement[0])append(ltbgt - Altbgt) $(replacement[1])append(Extra ltbgt - Bltbgt)

      replacement wil l be a dom element null or an array of dom elements return replacement)$(results)append(mappedItems)

      CSS

      body font-size16px ul floatleft margin0 30px colorblue results colorred

      HTML

      ltulgt ltligtFirstltl igt ltligtSecondltligt ltligtThirdltligt

      ltligtFourthltligt ltligtFifthltligt ltulgt ltul id=resultsgt

      ltulgt

      Example 3 Equalize the heights of the divs

      Javascript

      $fnequalizeHeights = function() var maxHeight = thismap(function(ie) return $(e)height() )get() return thisheight( Mathmaxapply(this maxHeight) )

      $( input)cl ick(function() $(div)equalizeHeights())

      CSS

      div width 40px floatleft input clearleft

      HTML

      ltinput type=button value=equalize div heightsgt

      ltdiv style=backgroundred height 40px gtltdivgtltdiv style=backgroundgreen height 70pxgtltdivgtltdiv style=backgroundblue height 50px gtltdivgt

      is

      Check the current matched set of elements against a selector element or jQuery object andreturn t rue if at least one of these elements matches the given arguments

      Added in version 16

      is(element)Boolean

      elementElement An element to match the current set of elements against

      Unlike other f iltering methods is() does not create a new jQuery object Instead it allows youto test the contents of a jQuery object without modif icat ion This is of ten useful insidecallbacks such as event handlers

      Suppose you have a list with two of its items containing a child element

      ltulgt ltligtlist ltstronggtitem 1ltstronggtltligt ltligtltspangtlist item 2ltspangtltligt ltligtlist item 3ltligtltulgt

      You can at tach a click handler to the ltulgt element and then limit the code to be triggered onlywhen a list item itself not one of its children is clicked

      $(ul)cl ick(function(event) var $target = $(eventtarget) i f ( $targetis( l i) ) $targetcss(background-color red) )

      Now when the user clicks on the word list in the f irst item or anywhere in the third item theclicked list item will be given a red background However when the user clicks on item 1 in thef irst item or anywhere in the second item nothing will occur because in those cases the targetof the event would be ltstronggt or ltspangt respect ively

      Be aware that for selector strings with posit ional selectors such as f irst gt() or even theposit ional f iltering is done against the jQuery object passed to is() not against the containingdocument So for the HTML shown above an expression such as $(lif irst)is(lilast) returnstrue but $(lif irst-child)is(lilast-child) returns false

      Using a Function

      The second form of this method evaluates expressions related to elements based on afunct ion rather than a selector For each element if the funct ion returns t rue is() returns t rueas well For example given a somewhat more involved HTML snippet

      ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

      You can at tach a click handler to every ltligt that evaluates the number of ltstronggt elementswithin the clicked ltligt at that t ime like so

      $(l i)cl ick(function() var $li = $(this) isWithTwo = $liis(function() return $(strong this)length === 2 ) i f ( isWithTwo ) $l i css(background-color green) else $l i css(background-color red) )

      Example 1 Shows a few ways is() can be used inside an event handler

      Javascript

      $(div)one(cl ick function () i f ($(this)is(first-child)) $(p)text(Its the first div) else if ($(this)is(bluered)) $(p)text(Its a blue or red div) else if ($(this)is(contains(Peter))) $(p)text(Its Peter) else $(p)html(Its nothing ltemgtspecialltemgt) $(p)hide()sl ideDown(slow) $(this)css(border-style inset cursordefault) )

      CSS

      div width60px height60px margin5px floatleft border4px outset backgroundgreen text-aligncenter font-weightbolder cursorpointer blue backgroundblue red backgroundred span colorwhite font-size16px p colorred font-weightbolder backgroundyellow margin3px clearleft displaynone

      HTML

      ltdivgtltdivgtltdiv class=bluegtltdivgtltdivgtltdivgtltdiv class=redgtltdivgt

      ltdivgtltbrgtltspangtPeterltspangtltdivgtltdiv class=bluegtltdivgtltpgtampnbspltpgt

      Example 2 Returns t rue because the parent of the input is a form element

      Javascript

      var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

      CSS

      div colorred

      HTML

      ltformgtltinput type=checkbox gtltformgtltdivgtltdivgt

      Example 3 Returns false because the parent of the input is a p element

      Javascript

      var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

      CSS

      div colorred

      HTML

      ltformgtltpgtltinput type=checkbox gtltpgtltformgt ltdivgtltdivgt

      Example 4 Checks against an exist ing collect ion of alternat ing list elements Blue alternat inglist elements slide up while others turn red

      Javascript

      var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() var $li = $(this) i f ( $l i is( $alt ) ) $l i sl ideUp() else $l i css(background red) )

      CSS

      l i cursorpointer

      HTML

      ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

      Example 5 An alternate way to achieve the above example using an element rather than ajQuery object Checks against an exist ing collect ion of alternat ing list elements Bluealternat ing list elements slide up while others turn red

      Javascript

      var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() i f ( $altis( this ) ) $(this)sl ideUp() else $(this)css(background red) )

      CSS

      l i cursorpointer

      HTML

      ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

      eq

      Reduce the set of matched elements to the one at the specif ied index

      Added in version 14

      eq(-index)jQuery

      -indexInteger

      An integer indicat ing the posit ion of the element count ing backwardsfrom the last element in the set

      Given a jQuery object that represents a set of DOM elements the eq() method constructs anew jQuery object f rom one element within that set The supplied index ident if ies the posit ionof this element in the set

      Consider a page with a simple list on it

      ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltulgt

      We can apply this method to the set of list items

      $( l i )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-basedand refers to the posit ion of the element within the jQuery object not within the DOM tree

      Providing a negat ive number indicates a posit ion start ing f rom the end of the set rather thanthe beginning For example

      $( l i )eq(-2)css(background-color red)

      This t ime list item 4 is turned red since it is two from the end of the set

      If an element cannot be found at the specif ied zero-based index the method constructs a newjQuery object with an empty set and a length property of 0

      $( l i )eq(5)css(background-color red)

      Here none of the list items is turned red since eq(5) indicates the sixth of f ive list items

      Example 1 Turn the div with index 2 blue by adding an appropriate class

      Javascript

      $(body)find(div)eq(2)addClass(blue)

      CSS

      div width60px height60px margin10px floatleft border2px solid blue blue backgroundblue

      HTML

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      filter

      Reduce the set of matched elements to those that match the selector or pass the funct ionstest

      Added in version 14

      f ilter(jQuery object)jQuery

      jQueryobject Object

      An exist ing jQuery object to match the current set of elementsagainst

      Given a jQuery object that represents a set of DOM elements the f ilter() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is tested

      new jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element all elements matching the selector will be included in the result

      Consider a page with a simple list on it

      list item 1

      list item 2

      list item 3

      list item 4

      list item 5

      list item 6

      We can apply this method to the set of list items

      $( l i )fi lter( 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 even and odd use 0-based indexing)

      Using a Filter Function

      The second form of this method allows us to f ilter elements against a funct ion rather than aselector For each element if the funct ion returns t rue (or a t ruthy value) the element will beincluded in the f iltered set otherwise it will be excluded Suppose we have a somewhat moreinvolved HTML snippet

      ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltligtlist item 6ltligtltulgt

      We can select the list items then f ilter them based on their contents

      $( l i )fi lter(function(index) return $(strong this)length == 1)css(background-color red)

      This code will alter the f irst list item only as it contains exact ly one ltstronggt tag Within the

      f ilter funct ion this refers to each DOM element in turn The parameter passed to the funct iontells us the index of that DOM element within the set matched by the jQuery object

      We can also take advantage of the index passed through the funct ion which indicates the 0-based posit ion of the element within the unf iltered set of matched elements

      $( l i )fi lter(function(index) return index 3 == 2)css(background-color red)

      This alterat ion to the code will cause the third and sixth list items to be highlighted as it usesthe modulus operator () to select every item with an index value that when divided by 3 hasa remainder of 2

      Example 1 Change the color of all divs then add a border to those with a middle class

      Javascript

      $(div)css(background c8ebcc) fi lter(middle) css(border-color red)

      CSS

      div width60px height60px margin5px floatleft border2px white solid

      HTML

      ltdivgtltdivgt

      ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt

      ltdivgtltdivgt

      Example 2 Change the color of all divs then add a border to the second one (index == 1) andthe div with an id of fourth

      Javascript

      $(div)css(background b4b0da) fi lter(function (index) return index == 1 || $(this)attr( id) == fourth ) css(border 3px double red)

      CSS

      div width60px height60px margin5px floatleft border3px white solid

      HTML

      ltdiv id=firstgtltdivgt ltdiv id=secondgtltdivgt ltdiv id=thirdgtltdivgt

      ltdiv id=fourthgtltdivgt ltdiv id=fifthgtltdivgt ltdiv id=sixthgtltdivgt

      Example 3 Select all divs and f ilter the select ion with a DOM element keeping only the one withan id of unique

      Javascript

      $(div)fi lter( documentgetElementById(unique) )

      Example 4 Select all divs and f ilter the select ion with a jQuery object keeping only the one withan id of unique

      Javascript

      $(div)fi lter( $(unique) )

      Attributes

      removeProp

      Remove a property for the set of matched elements

      Added in version 16

      removeProp(propertyName)jQuery

      propertyNameString The name of the property to set

      The removeProp() method removes propert ies set by the prop() method

      With some built -in propert ies of a DOM element or window object browsers may generate anerror if an at tempt is made to remove the property jQuery f irst assigns the value undef ined tothe property and ignores any error the browser generates In general it is only necessary toremove custom propert ies that have been set on an object and not built -in (nat ive) propert ies

      Note Do not use this method to remove nat ive propert ies such as checked disabled orselected This will remove the property completely and once removed cannot be added againto element Use prop() to set these propert ies to false instead

      Example 1 Set a numeric property on a paragraph and then remove it

      Javascript

      var $para = $(p)$paraprop(luggageCode 1234)$paraappend(The secret luggage code is String($paraprop(luggageCode)) )$pararemoveProp(luggageCode)$paraappend(Now the secret luggage code is String($paraprop(luggageCode)) )

      CSS

      img padding10px div colorred font-size24px

      HTML

      ltpgtltpgt

      prop

      Get the value of a property for the f irst element in the set of matched elements

      Added in version 16

      prop(propertyName)String

      propertyNameString The name of the property to get

      The prop() method gets the property value for only the first element in the matched set Itreturns undef ined for the value of a property that has not been set or if the matched set hasno elements To get the value for each element individually use a looping construct such asjQuerys each() or map() method

      The dif ference between attributes and properties can be important in specif ic situat ions BeforejQuery 16 the at t r() method sometimes took property values into account when retrievingsome attributes which could cause inconsistent behavior As of jQuery 16 the prop() methodprovides a way to explicit ly retrieve property values while at t r() retrieves at t ributes

      For example selectedIndex tagName nodeName nodeType ownerDocumentdefaultChecked and defaultSelected should be retrieved and set with the prop() method Priorto jQuery 16 these propert ies were retrievable with the at t r() method but this was not withinthe scope of at t r These do not have corresponding at t ributes and are only propert ies

      Concerning boolean at t ributes consider a DOM element def ined by the HTML markup ltinputtype=checkbox checked=checked gt and assume it is in a JavaScript variable named elem

      elemchecked t rue (Boolean) Will change with checkbox state

      $(elem)prop(checked) t rue (Boolean) Will change with checkbox state

      elemgetAttribute(checked)checked (String) Init ial state of the checkbox doesnot change

      $(elem)attr(checked)(16)checked (String) Init ial state of the checkbox doesnot change

      $(elem)attr(checked)(161+) checked (String) Will change with checkbox state

      $(elem)attr(checked)(pre-16)

      t rue (Boolean) Changed with checkbox state

      According to the W3C forms specif icat ion the checked at t ribute is a boolean attribute whichmeans the corresponding property is t rue if the at t ribute is present at allacirceurordquoeven if for examplethe at t ribute has no value or an empty string value The preferred cross-browser-compat ibleway to determine if a checkbox is checked is to check for a t ruthy value on the element sproperty using one of the following

      if ( elemchecked )

      if ( $(elem)prop(checked) )

      if ( $(elem)is(checked) )

      If using jQuery 16 the code if ( $(elem)at t r(checked) ) will retrieve the actual content attributewhich does not change as the checkbox is checked and unchecked It is meant only to storethe default or init ial value of the checked property To maintain backwards compatability theat t r() method in jQuery 161+ will retrieve and update the property for you so no code forboolean at t ributes is required to be changed to prop() Nevertheless the preferred way toretrieve a checked value is with one of the opt ions listed above To see how this works in thelatest jQuery checkuncheck the checkbox in the example below

      Example 1 Display the checked property and at t ribute of a checkbox as it changes

      Javascript

      $(input)change(function() var $input = $(this) $(p)html(attr(checked) ltbgt + $inputattr(checked) + ltbgtltbrgt + prop(checked) ltbgt + $inputprop(checked) + ltbgtltbrgt + is( checked) ltbgt + $inputis( checked) ) + ltbgt)change()

      CSS

      p margin 20px 0 0 b color blue

      HTML

      ltinput id=check1 type=checkbox checked=checkedgtltlabel for=check1gtCheck meltlabelgtltpgtltpgt

      prop

      Set one or more propert ies for the set of matched elements

      Added in version 16

      prop(propertyName funct ion(index oldPropertyValue))jQuery

      propertyNameString The name of the property to set

      funct ion(indexoldPropertyValue)Funct ion

      A funct ion returning the value to set Receives the indexposit ion of the element in the set and the old propertyvalue as arguments Within the funct ion the keyword thisrefers to the current element

      The prop() method is a convenient way to set the value of propert iesacirceurordquoespecially whensett ing mult iple propert ies using values returned by a funct ion or set t ing values on mult ipleelements at once It should be used when sett ing selectedIndex tagName nodeNamenodeType ownerDocument defaultChecked or defaultSelected Since jQuery 16 thesepropert ies can no longer be set with the at t r() method They do not have correspondingattributes and are only propert ies

      Propert ies generally af fect the dynamic state of a DOM element without changing theserialized HTML attribute Examples include the value property of input elements the disabledproperty of inputs and buttons or the checked property of a checkbox The prop() methodshould be used to set disabled and checked instead of the at t r() method The val() methodshould be used for gett ing and sett ing value

      $(input)prop(disabled false)$(input)prop(checked true)$(input)val(someValue)

      Important the removeProp() method should not be used to set these propert ies to false Oncea nat ive property is removed it cannot be added again See removeProp() for moreinformat ion

      Computed property values

      By using a funct ion to set propert ies you can compute the value based on other propert ies ofthe element For example to toggle all checkboxes based of f their individual values

      $(input[type=checkbox])prop(checked function( i val ) return val)

      Note If nothing is returned in the setter funct ion (ie funct ion(index prop)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

      Example 1 Disable all checkboxes on the page

      Javascript

      $(input[type=checkbox])prop( disabled true)

      CSS

      img padding10px div colorred font-size24px

      HTML

      ltinput type=checkbox checked=checked gt ltinput type=checkbox gt ltinput type=checkbox gt ltinput type=checkbox checked=checked gt

      val

      Get the current value of the f irst element in the set of matched elements

      Added in version 10

      val()String Number Array

      The val() method is primarily used to get the values of form elements In the case of ltselectmult iple=mult iplegt elements the val() method returns an array containing each selectedopt ion

      For selects and checkboxes you can also use the selected and checked selectors to get atvalues for example

      $(selectfoo optionselected)val() get the value from a dropdown select$(selectfoo)val() get the value from a dropdown select even easier$( inputcheckboxchecked)val() get the value from a checked checkbox$( inputradio[name=bar]checked)val() get the value from a set of radio buttons

      Example 1 Get the single value from a single select and an array of values from a mult ipleselect and display their values

      Javascript

      function displayVals() var singleValues = $(single)val() var multipleValues = $(multiple)val() || [] $(p)html(ltbgtSingleltbgt + singleValues + ltbgtMultipleltbgt + multipleValuesjoin( ))

      $(select)change(displayVals) displayVals()

      CSS

      p colorred margin4px b colorblue

      HTML

      ltpgtltpgt ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

      ltselectgt ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

      ltoption selected=selectedgtMultiple3ltoptiongt ltselectgt

      Example 2 Find the value of an input box

      Javascript

      $(input)keyup(function () var value = $(this)val() $(p)text(value) )keyup()

      CSS

      p colorblue margin8px

      HTML

      ltinput type=text value=some textgt ltpgtltpgt

      val

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

      Added in version 14

      val(funct ion(index value))jQuery

      funct ion(indexvalue)Funct ion

      A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the old valueas arguments

      This method is typically used to set the values of form f ields

      Passing an array of element values allows matching ltinput type=checkboxgt ltinputtype=radiogt and ltopt iongts inside of n ltselect mult iple=mult iplegt to be selected In the caseof ltinput type=radiogts that are part of a radio group and ltselect mult iple=mult iplegt theother elements will be deselected

      The val() method allows us to set the value by passing in a funct ion As of jQuery 14 thefunct ion is passed two arguments the current element s index and its current value

      $( inputtextitems)val(function(index value) return value + + thisclassName)

      This example appends the string items to the text inputs values

      Example 1 Set the value of an input box

      Javascript

      $(button)cl ick(function () var text = $(this)text() $(input)val(text) )

      CSS

      button margin4px cursorpointer input margin4px colorblue

      HTML

      ltdivgt ltbuttongtFeedltbuttongt ltbuttongttheltbuttongt

      ltbuttongtInputltbuttongt ltdivgt ltinput type=text value=click a button gt

      Example 2 Use the funct ion argument to modify the value of an input box

      Javascript

      $( input)bind(blur function() $(this)val(function(i val) return valtoUpperCase() ) )

      HTML

      ltpgtType something and then click or tab out of the inputltpgt ltinput type=text value=type something gt

      Example 3 Set a single select a mult iple select checkboxes and a radio button

      Javascript

      $(single)val(Single2) $(multiple)val([Multiple2 Multiple3]) $(input)val([check1check2 radio1 ])

      CSS

      body colorblue

      HTML

      ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

      ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

      ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=checkboxname value=check1gt check1 ltinput type=checkbox name=checkboxname value=check2gt check2 ltinput type=radio name=r value=radio1gt radio1 ltinput type=radio name=r value=radio2gt radio2

      html

      Get the HTML contents of the f irst element in the set of matched elements

      Added in version 10

      html()String

      This method is not available on XML documents

      In an HTML document html() can be used to get the contents of any element If the selectorexpression matches more than one element only the f irst match will have its HTML contentreturned Consider this code

      $(divdemo-container)html()

      In order for the following ltdivgts content to be retrieved it would have to be the f irst one withclass=demo-container in the document

      ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

      The result would look like this

      ltdiv class=demo-boxgtDemonstration Boxltdivgt

      This method uses the browsers innerHTML property Some browsers may not return HTML

      that exact ly replicates the HTML source in an original document For example Internet Explorersometimes leaves of f the quotes around at t ribute values if they contain only alphanumericcharacters

      Example 1 Click a paragraph to convert it f rom html to text

      Javascript

      $(p)cl ick(function () var htmlStr = $(this)html() $(this)text(htmlStr) )

      CSS

      p margin8px font-size20px colorblue cursorpointer b text-decorationunderline button cursorpointer

      HTML

      ltpgt

      ltbgtClickltbgt to change the ltspan id=taggthtmlltspangt ltpgt ltpgt

      to a ltspan id=textgttextltspangt node ltpgt ltpgt This ltbutton name=nadagtbuttonltbuttongt does nothing ltpgt

      html

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

      Added in version 14

      html(funct ion(index oldhtml))jQuery

      funct ion(indexoldhtml)Funct ion

      A funct ion returning the HTML content to set Receives the indexposit ion of the element in the set and the old HTML value asarguments jQuery empt ies the element before calling the funct ionuse the oldhtml argument to reference the previous content Withinthe funct ion this refers to the current element in the set

      The html() method is not available in XML documents

      When html() is used to set an element s content any content that was in that element iscompletely replaced by the new content Consider the following HTML

      ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

      The content of ltdiv class=demo-containergt can be set like this

      $(divdemo-container) html(ltpgtAll new content ltemgtYou betltemgtltpgt)

      That line of code will replace everything inside ltdiv class=demo-containergt

      ltdiv class=demo-containergt ltpgtAll new content ltemgtYou betltemgtltpgtltdivgt

      As of jQuery 14 the html() method allows the HTML content to be set by passing in afunct ion

      $(divdemo-container)html(function() var emph = ltemgt + $(p)length + paragraphsltemgt return ltpgtAll new content for + emph + ltpgt)

      Given a document with six paragraphs this example will set the HTML of ltdiv class=demo-containergt to ltpgtAll new content for ltemgt6 paragraphsltemgtltpgt

      This method uses the browsers innerHTML property Some browsers may not generate a DOMthat exact ly replicates the HTML source provided For example Internet Explorer prior toversion 8 will convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

      Example 1 Add some html to each div

      Javascript

      $(div)html(ltspan class=redgtHello ltbgtAgainltbgtltspangt)

      CSS

      red colorred

      HTML

      ltspangtHelloltspangt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      Example 2 Add some html to each div then immediately do further manipulat ions to theinserted html

      Javascript

      $(div)html(ltbgtWowltbgt Such excitement) $(div b)append(documentcreateTextNode()) css(color red)

      CSS

      div colorblue font-size18px

      HTML

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      toggleClass

      Add or remove one or more classes from each element in the set of matched elementsdepending on either the classs presence or the value of the switch argument

      Added in version 14

      toggleClass(funct ion(index class switch) switch)jQuery

      funct ion(indexclassswitch)Funct ion

      A funct ion that returns class names to be toggled in the classattribute of each element in the matched set Receives the indexposit ion of the element in the set the old class value and the switchas arguments

      switchBoolean (opt ional) A boolean value to determine whether the class should beadded or removed

      This method takes one or more class names as its parameter In the f irst version if an elementin the matched set of elements already has the class then it is removed if an element does nothave the class then it is added For example we can apply toggleClass() to a simple ltdivgt

      ltdiv class=tumblegtSome textltdivgt

      The f irst t ime we apply $(divtumble)toggleClass(bounce) we get the following

      ltdiv class=tumble bouncegtSome textltdivgt

      The second t ime we apply $(divtumble)toggleClass(bounce) the ltdivgt class is returned tothe single tumble value

      ltdiv class=tumblegtSome textltdivgt

      Applying toggleClass(bounce spin) to the same ltdivgt alternates between ltdiv class=tumblebounce spingt and ltdiv class=tumblegt

      The second version of toggleClass() uses the second parameter for determining whether theclass should be added or removed If this parameters value is t rue then the class is added iffalse the class is removed In essence the statement

      $(foo)toggleClass(className addOrRemove)

      is equivalent to

      i f (addOrRemove) $(foo)addClass(className) else $(foo)removeClass(className)

      As of jQuery 14 if no arguments are passed to toggleClass() all class names on the elementthe f irst t ime toggleClass() is called will be toggled Also as of jQuery 14 the class name to be

      toggled can be determined by passing in a funct ion

      $(divfoo)toggleClass(function() if ($(this)parent()is( bar)) return happy else return sad )

      This example will toggle the happy class for ltdiv class=foogt elements if their parent elementhas a class of bar otherwise it will toggle the sad class

      Example 1 Toggle the class highlight when a paragraph is clicked

      Javascript

      $(p)cl ick(function () $(this)toggleClass(highlight) )

      CSS

      p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundyellow

      HTML

      ltp class=bluegtClick to toggleltpgt ltp class=blue highlightgthighlightltpgt ltp class=bluegton theseltpgt ltp class=bluegtparagraphsltpgt

      Example 2 Add the highlight class to the clicked paragraph on every third click of thatparagraph remove it every f irst and second click

      Javascript

      var count = 0$(p)each(function() var $thisParagraph = $(this) var count = 0 $thisParagraphclick(function() count++ $thisParagraphfind(span)text(cl icks + count) $thisParagraphtoggleClass(highlight count 3 == 0) ))

      CSS

      p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundred

      HTML

      ltp class=bluegtClick to toggle (ltspangtclicks 0ltspangt)ltpgt ltp class=blue highlightgthighlight (ltspangtclicks 0ltspangt)ltpgt ltp class=bluegton these (ltspangtclicks 0ltspangt)ltpgt

      ltp class=bluegtparagraphs (ltspangtclicks 0ltspangt)ltpgt

      Example 3 Toggle the class name(s) indicated on the buttons for each div

      CSS

      wrap gt div float left width 100px margin 1em 1em 0 0 padding=left 3px border 1px solid abc diva background-color aqua divb background-color burlywood divc background-color cornsilk

      HTML

      ltdiv class=buttonsgt ltbuttongttoggleltbuttongt ltbutton class=agttoggle altbuttongt ltbutton class=a bgttoggle a bltbuttongt ltbutton class=a b cgttoggle a b cltbuttongt lta href=gtresetltagtltdivgtltdiv class=wrapgt ltdivgtltdivgt ltdiv class=bgtltdivgt ltdiv class=a bgtltdivgt ltdiv class=a cgtltdivgtltdivgt

      Javascript

      var cls = [ a a b a b c]var divs = $(divwrap)children()var appendClass = function() divsappend(function() return ltdivgt + (thisclassName || none) + ltdivgt )

      appendClass()

      $(button)bind(cl ick function() var tc = thisclassName || undefined divstoggleClass(tc) appendClass())

      $(a)bind(cl ick function(event) eventpreventDefault() divsempty()each(function(i) thisclassName = cls[i] ) appendClass())

      removeClass

      Remove a single class mult iple classes or all classes from each element in the set of matchedelements

      Added in version 14

      removeClass(funct ion(index class))jQuery

      funct ion(index A funct ion returning one or more space-separated class names to be

      class)Funct ion removed Receives the index posit ion of the element in the set and theold class value as arguments

      If a class name is included as a parameter then only that class will be removed from the set ofmatched elements If no class names are specif ied in the parameter all classes will be removed

      More than one class may be removed at a t ime separated by a space f rom the set of matchedelements like so

      $(p)removeClass(myClass yourClass)

      This method is of ten used with addClass() to switch elements classes from one to anotherlike so

      $(p)removeClass(myClass noClass)addClass(yourClass)

      Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

      To replace all exist ing classes with another class we can use at t r(class newClass) instead

      As of jQuery 14 the removeClass() method allows us to indicate the class to be removed bypassing in a funct ion

      $( l i last)removeClass(function() return $(this)prev()attr(class) )

      This example removes the class name of the penult imate ltligt f rom the last ltligt

      Example 1 Remove the class blue f rom the matched elements

      Javascript

      $(peven)removeClass(blue)

      CSS

      p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

      HTML

      ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

      ltp class=blue undergtGoodbyeltpgt

      Example 2 Remove the class blue and under f rom the matched elements

      Javascript

      $(podd)removeClass(blue under)

      CSS

      p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

      HTML

      ltp class=blue undergtHelloltpgt

      ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt ltp class=blue undergtGoodbyeltpgt

      Example 3 Remove all the classes from the matched elements

      Javascript

      $(peq(1))removeClass()

      CSS

      p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

      HTML

      ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

      ltp class=blue undergtGoodbyeltpgt

      hasClass

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

      Added in version 12

      hasClass(className)Boolean

      classNameString The class name to search for

      Elements may have more than one class assigned to them In HTML this is represented byseparat ing the class names with a space

      ltdiv id=mydiv class=foo bargtltdivgt

      The hasClass() method will return t rue if the class is assigned to an element even if otherclasses also are For example given the HTML above the following will return t rue

      $(mydiv)hasClass(foo)

      As would

      $(mydiv)hasClass(bar)

      While this would return false

      $(mydiv)hasClass(quux)

      Example 1 Looks for the paragraph that contains selected as a class

      Javascript

      $(divresult1)append($(pfirst)hasClass(selected)toString())$(divresult2)append($(plast)hasClass(selected)toString())$(divresult3)append($(p)hasClass(selected)toString())

      CSS

      p margin 8px font-size16px selected colorred

      HTML

      ltpgtThis paragraph is black and is the first paragraphltpgt ltp class=selectedgtThis paragraph is red and is the second paragraphltpgt

      ltdiv id=result1gtFirst paragraph has selected class ltdivgt ltdiv id=result2gtSecond paragraph has selected class ltdivgt ltdiv id=result3gtAt least one paragraph has selected class ltdivgt

      removeAttr

      Remove an at t ribute f rom each element in the set of matched elements

      Added in version 10

      removeAttr(at t ributeName)jQuery

      attributeNameString An at t ribute to remove

      The removeAttr() method uses the JavaScript removeAttribute() funct ion but it has theadvantage of being able to be called direct ly on a jQuery object and it accounts for dif ferentat t ribute naming across browsers

      NoteIf at tempt ing to remove an inline onclick event handler using removeAttr() one may f indthat this doesnt achieve the desired ef fect in Internet Explorer 67 or 8 Instead it isrecommended to opt for using prop() to achieve this as follows

      $elementprop(onclick null)consolelog(onclick property $element[0]onclick)

      We may update the behavior of removeAttr() at some point in the future to better handle thishowever for the t ime being the above should be considered the standard cross-browserapproach to this problem

      Example 1 Clicking the button enables the input next to it

      Javascript

      $(button)cl ick(function () $(this)next()removeAttr(disabled) focus() val(editable now))

      HTML

      ltbuttongtEnableltbuttongtltinput type=text disabled=disabled value=cant edit this gt

      attr

      Get the value of an at t ribute for the f irst element in the set of matched elements

      Added in version 10

      attr(at t ributeName)String

      attributeNameString The name of the at t ribute to get

      The at t r() method gets the at t ribute value for only the first element in the matched set To getthe value for each element individually use a looping construct such as jQuerys each() ormap() method

      As of jQuery 16 the at t r() method returns undef ined for at t ributes that have not been set Inaddit ion at t r() should not be used on plain objects arrays the window or the document Toretrieve and change DOM propert ies use the prop() method

      Using jQuerys at t r() method to get the value of an element s at t ribute has two main benef its

      1 Convenience It can be called direct ly on a jQuery object and chained to other jQuerymethods

      2 Cross-browser consistency The values of some attributes are reported inconsistent lyacross browsers and even across versions of a single browser The at t r() methodreduces such inconsistencies

      Note Attribute values are strings with the exception of a few attributes such asvalue and tabindex

      Example 1 Find the t it le at t ribute of the f irst in the page

      Javascript

      var title = $(em)attr(title) $(div)text(title)

      CSS

      em colorblue font-weightbold div colorred

      HTML

      ltpgt Once there was a ltem title=huge giganticgtlargeltemgt dinosaurltpgt

      The title of the emphasis isltdivgtltdivgt

      attr

      Set one or more at t ributes for the set of matched elements

      Added in version 11

      attr(at t ributeName funct ion(index at t r))jQuery

      attributeNameString The name of the at t ribute to set

      funct ion(indexat t r)Funct ion

      A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the oldattribute value as arguments

      The at t r() method is a convenient way to set the value of at t ributesacirceurordquoespecially when sett ingmult iple at t ributes or using values returned by a funct ion Consider the following image

      ltimg id=greatphoto src=brush-sellerjpg alt=brush seller gt

      Setting a simple attribute

      To change the alt at t ribute simply pass the name of the at t ribute and its new value to theat t r() method

      $(greatphoto)attr(alt Beij ing Brush Seller)

      Add an at t ribute the same way

      $(greatphoto)attr(title Photo by Kelly Clark)

      Setting several attributes at once

      To change the alt at t ribute and add the t it le at t ribute at the same t ime pass both sets ofnames and values into the method at once using a map (JavaScript object literal) Each key-value pair in the map adds or modif ies an at t ribute

      $(greatphoto)attr( alt Beij ing Brush Seller title photo by Kelly Clark)

      When sett ing mult iple at t ributes the quotes around at t ribute names are opt ional

      WARNING When sett ing the class at t ribute you must always use quotes

      Note jQuery prohibits changing the type at t ribute on an ltinputgt or ltbuttongt element and willthrow an error in all browsers This is because the type at t ribute cannot be changed in InternetExplorer

      Computed attribute values

      By using a funct ion to set at t ributes you can compute the value based on other propert ies ofthe element For example to concatenate a new value with an exist ing value

      $(greatphoto)attr(title function(i val) return val + - photo by Kelly Clark)

      This use of a funct ion to compute at t ribute values can be part icularly useful when modifyingthe at t ributes of mult iple elements at once

      Note If nothing is returned in the setter funct ion (ie funct ion(index at t r)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

      Example 1 Set some attributes for all s in the page

      Javascript

      $(img)attr( src imageshatgif title jQuery alt jQuery Logo)$(div)text($(img)attr(alt))

      CSS

      img padding10px div colorred font-size24px

      HTML

      ltimg gt ltimg gt ltimg gt

      ltdivgtltBgtAttribute of AjaxltBgtltdivgt

      Example 2 Disable buttons greater than the 1st button

      Javascript

      $(buttongt(1))attr(disableddisabled)

      CSS

      button margin10px

      HTML

      ltbuttongt0th Buttonltbuttongt ltbuttongt1st Buttonltbuttongt ltbuttongt2nd Buttonltbuttongt

      Example 3 Set the id for divs based on the posit ion in the page

      Javascript

      $(div)attr( id function (arr) return div-id + arr)each(function () $(span this)html((ID = ltbgt + thisid + ltbgt)))

      CSS

      div colorblue span colorred b font-weightbolder

      HTML

      ltdivgtZero-th ltspangtltspangtltdivgt ltdivgtFirst ltspangtltspangtltdivgt ltdivgtSecond ltspangtltspangtltdivgt

      Example 4 Set the src at t ribute f rom t it le at t ribute on the image

      Javascript

      $(img)attr(src function() return images + thistitle )

      HTML

      ltimg title=hatgifgt

      addClass

      Adds the specif ied class(es) to each of the set of matched elements

      Added in version 14

      addClass(funct ion(index currentClass))jQuery

      funct ion(indexcurrentClass)Funct ion

      A funct ion returning one or more space-separated class namesto be added to the exist ing class name(s) Receives the indexposit ion of the element in the set and the exist ing class name(s)as arguments Within the funct ion this refers to the currentelement in the set

      It s important to note that this method does not replace a class It simply adds the classappending it to any which may already be assigned to the elements

      More than one class may be added at a t ime separated by a space to the set of matchedelements like so

      $(p)addClass(myClass yourClass)

      This method is of ten used with removeClass() to switch elements classes from one toanother like so

      $(p)removeClass(myClass noClass)addClass(yourClass)

      Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

      As of jQuery 14 the addClass() methods argument can receive a funct ion

      $(ul l i last)addClass(function() return item- + $(this)index())

      Given an unordered list with f ive ltligt elements this example adds the class item-4 to the lastltligt

      Example 1 Adds the class selected to the matched elements

      Javascript

      $(plast)addClass(selected)

      CSS

      p margin 8px font-size16px selected colorblue highlight backgroundyellow

      HTML

      ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

      Example 2 Adds the classes selected and highlight to the matched elements

      Javascript

      $(plast)addClass(selected highlight)

      CSS

      p margin 8px font-size16px selected colorred highlight backgroundyellow

      HTML

      ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

      Example 3 Pass in a funct ion to addClass() to add the green class to a div that already has ared class

      Javascript

      $(div)addClass(function(index currentClass) var addedClass

      i f ( currentClass === red ) addedClass = green $(p)text(There is one green div) return addedClass )

      CSS

      div background white red background red redgreen background green

      HTML

      ltdivgtThis div should be whiteltdivgt ltdiv class=redgtThis div wil l be green because it now has the green and red classes It would be red if the addClass function failedltdivgt ltdivgtThis div should be whiteltdivgt ltpgtThere are zero green divsltpgt

      CSS

      jQuerycssHooks

      Hook direct ly into jQuery to override how part icular CSS propert ies are retrieved or set normalize CSS property naming or create custom propert ies

      Added in version 143

      The $cssHooks object provides a way to def ine funct ions for gett ing and sett ing part icularCSS values It can also be used to create new cssHooks for normalizing CSS3 features such asbox shadows and gradients

      For example some versions of Webkit -based browsers require -webkit -border-radius to set theborder-radius on an element while earlier Firefox versions require -moz-border-radius AcssHook can normalize these vendor-pref ixed propert ies to let css() accept a single standardproperty name (border-radius or with DOM property syntax borderRadius)

      In addit ion to providing f ine-grained control over how specif ic style propert ies are handled$cssHooks also extends the set of propert ies available to the animate() method

      Def ining a new cssHook is straight-forward The skeleton template below can serve as a guideto creat ing your own

      (function($) first check to see if cssHooks are supported if ( $cssHooks ) i f not output an error message throw(jQuery 143 or above is required for this plugin to work) return

      $cssHooks[someCSSProp] = get function( elem computed extra ) handle getting the CSS property set function( elem value ) handle setting the CSS value )(jQuery)

      Feature Testing

      Before normalizing a vendor-specif ic CSS property f irst determine whether the browsersupports the standard property or a vendor-pref ixed variat ion For example to check forsupport of the border-radius property see if any variat ion is a member of a temporary

      element s style object

      (function($) function styleSupport( prop ) var vendorProp supportedProp

      capitalize first character of the prop to test vendor prefix capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

      i f ( prop in divstyle )

      browser supports standard CSS property name supportedProp = prop else

      otherwise test support for vendor-prefixed property names for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

      avoid memory leak in IE div = null add property to $support so it can be accessed elsewhere $support[ prop ] = supportedProp return supportedProp

      call the function eg testing for border-radius support styleSupport( borderRadius ))(jQuery)

      Defining a complete cssHook

      To def ine a complete cssHook combine the support test with a f illed-out version of theskeleton template provided in the f irst example

      (function($) if ( $cssHooks ) throw(jQuery 143+ is needed for this plugin to work) return function styleSupport( prop ) var vendorProp supportedProp capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

      i f ( prop in divstyle ) supportedProp = prop else for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

      div = null $support[ prop ] = supportedProp return supportedProp

      var borderRadius = styleSupport( borderRadius )

      Set cssHooks only for browsers that support a vendor-prefixed border radius if ( borderRadius ampamp borderRadius == borderRadius ) $cssHookborderRadius = get function( elem computed extra ) return $css( elem borderRadius ) set function( elem value) elemstyle[ borderRadius ] = value )(jQuery)

      You can then set the border radius in a supported browser using either the DOM (camelCased)style or the CSS (hyphenated) style

      $(element)css(borderRadius 10px)$(another)css(border-radius 20px)

      If the browser lacks support for any form of the CSS property vendor-pref ixed or not the styleis not applied to the element However if the browser supports a proprietary alternat ive it canbe applied to the cssHooks instead

      (function($) feature test for support of a CSS property and a proprietary alternative

      i f ( $supportsomeCSSProp ampamp $supportsomeCSSProp == someCSSProp )

      Set cssHooks for browsers that support only a vendor-prefixed someCSSProp $cssHooksomeCSSProp = get function( elem computed extra ) return $css( elem $supportsomeCSSProp ) set function( elem value) elemstyle[ $supportsomeCSSProp ] = value else if ( supportsProprietaryAlternative ) $cssHooksomeCSSProp = get function( elem computed extra ) Handle crazy conversion from the proprietary alternative set function( elem value ) Handle crazy conversion to the proprietary alternative

      )(jQuery)

      Special units

      By default jQuery adds a px unit to the values passed to the css() method This behavior canbe prevented by adding the property to the jQuerycssNumber object

      $cssNumber[someCSSProp] = true

      Animating with cssHooks

      A cssHook can also hook into jQuerys animat ion mechanism by adding a property to thejQueryfxstep object

      $fxstep[someCSSProp] = function(fx) $cssHooks[someCSSProp]set( fxelem fxnow + fxunit )

      Note that this works best for simple numeric-value animat ions More custom code may berequired depending on the CSS property the type of value it returns and the animat ionscomplexity

      outerWidth

      Get the current computed width for the f irst element in the set of matched elements includingpadding and border

      Added in version 126

      outerWidth(includeMargin)Integer

      includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

      Returns the width of the element along with lef t and right padding border and opt ionallymargin in pixels

      If includeMargin is omit ted or false the padding and border are included in the calculat ion ift rue the margin is also included

      This method is not applicable to window and document objects for these use width() instead

      Example 1 Get the outerWidth of a paragraph

      Javascript

      var p = $(pfirst)$(plast)text( outerWidth + pouterWidth()+ outerWidth(true) + pouterWidth(true) )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      outerHeight

      Get the current computed height for the f irst element in the set of matched elements includingpadding border and opt ionally margin

      Added in version 126

      outerHeight(includeMargin)Integer

      includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

      The top and bottom padding and border are always included in the outerHeight() calculat ion ifthe includeMargin argument is set to t rue the margin (top and bottom) is also included

      This method is not applicable to window and document objects for these use height() instead

      Example 1 Get the outerHeight of aparagraph

      Javascript

      var p = $(pfirst)$(plast)text( outerHeight + pouterHeight() + outerHeight(true) + pouterHeight(true) )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      innerWidth

      Get the current computed width for the f irst element in the set of matched elements includingpadding but not border

      Added in version 126

      innerWidth()Integer

      This method returns the width of the element including lef t and right padding in pixels

      This method is not applicable to window and document objects for these use width() instead

      Example 1 Get the innerWidth of a paragraph

      Javascript

      var p = $(pfirst)$(plast)text( innerWidth + pinnerWidth() )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      innerHeight

      Get the current computed height for the f irst element in the set of matched elements includingpadding but not border

      Added in version 126

      innerHeight()Integer

      This method returns the height of the element including top and bottom padding in pixels

      This method is not applicable to window and document objects for these use height() instead

      Example 1 Get the innerHeight of aparagraph

      Javascript

      var p = $(pfirst)$(plast)text( innerHeight + pinnerHeight() )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      width

      Get the current computed width for the f irst element in the set of matched elements

      Added in version 10

      width()Integer

      The dif ference between css(width) and width() is that the lat ter returns a unit -less pixel value(for example 400) while the former returns a value with units intact (for example 400px) Thewidth() method is recommended when an element s width needs to be used in a mathematicalcalculat ion

      This method is also able to f ind the width of thewindow and document

      $(window)width() returns width of browser viewport$(document)width() returns width of HTML document

      Note that width() will always return the content width regardless of the value of the CSS box-sizing property

      Example 1 Show various widths Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

      Javascript

      function showWidth(ele w) $(div)text(The width for the + ele + is + w + px) $(getp)cl ick(function () showWidth(paragraph $(p)width()) ) $(getd)cl ick(function () showWidth(document $(document)width()) ) $(getw)cl ick(function () showWidth(window $(window)width()) )

      CSS

      body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

      HTML

      ltbutton id=getpgtGet Paragraph Widthltbuttongt ltbutton id=getdgtGet Document Widthltbuttongt ltbutton id=getwgtGet Window Widthltbuttongt

      ltdivgtampnbspltdivgt ltpgt Sample paragraph to test width ltpgt

      width

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

      Added in version 141

      width(funct ion(index width))jQuery

      funct ion(indexwidth)Funct ion

      A funct ion returning the width to set Receives the index posit ion ofthe element in the set and the old width as arguments Within thefunct ion this refers to the current element in the set

      When calling width(value) the value can be either a string (number and unit ) or a number Ifonly 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 100px 50 or auto)Note that in modern browsers the CSS width property does not include padding border ormargin unless the box-sizing CSS property is used

      If no explicit unit was specif ied (like em or ) then px is concatenated to the value

      Note that width(value) sets the width of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterWidth of the box instead of the content width

      Example 1 To set the width of each div on click to 30px plus a color change

      Javascript

      $(div)one(cl ick function () $(this)width(30) css(cursorauto background-colorblue) )

      CSS

      div width70px height50px floatleft margin5px backgroundred cursorpointer

      HTML

      ltdivgtltdivgt ltdivgtdltdivgt

      ltdivgtdltdivgt ltdivgtdltdivgt ltdivgtdltdivgt

      height

      Get the current computed height for the f irst element in the set of matched elements

      Added in version 10

      height()Integer

      The dif ference between css(height ) and height() is that the lat ter returns a unit -less pixelvalue (for example 400) while the former returns a value with units intact (for example 400px)The height() method is recommended when an element s height needs to be used in amathematical calculat ion

      This method is also able to f ind the heightof the window and document

      $(window)height() returns height of browser viewport$(document)height() returns height of HTML document

      Note that height() will always return the content height regardless of the value of the CSSbox-sizing property

      Example 1 Show various heights Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

      Javascript

      function showHeight(ele h) $(div)text(The height for the + ele + is + h + px) $(getp)cl ick(function () showHeight(paragraph $(p)height()) ) $(getd)cl ick(function () showHeight(document $(document)height()) ) $(getw)cl ick(function () showHeight(window $(window)height()) )

      CSS

      body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

      HTML

      ltbutton id=getpgtGet Paragraph Heightltbuttongt ltbutton id=getdgtGet Document Heightltbuttongt ltbutton id=getwgtGet Window Heightltbuttongt

      ltdivgtampnbspltdivgt ltpgt Sample paragraph to test height ltpgt

      height

      Set the CSS height of every matched element

      Added in version 141

      height(funct ion(index height))jQuery

      funct ion(indexheight)Funct ion

      A funct ion returning the height to set Receives the index posit ion ofthe element in the set and the old height as arguments Within thefunct ion this refers to the current element in the set

      When calling height(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is providedhowever a valid CSS measurement must be provided for the height (such as 100px 50 orauto) Note that in modern browsers the CSS height property does not include paddingborder or margin

      If no explicit unit was specif ied (like em or ) then px is concatenated to the value

      Note that height(value) sets the height of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterHeight of the box instead of the content height

      Example 1 To set the height of each div on click to 30px plus a color change

      Javascript

      $(div)one(cl ick function () $(this)height(30) css(cursorauto backgroundColorgreen) )

      CSS

      div width50px height70px floatleft margin5px backgroundrgb(2551400) cursorpointer

      HTML

      ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      scrollLeft

      Get the current horizontal posit ion of the scroll bar for the f irst element in the set of matchedelements

      Added in version 126

      scrollLef t ()Integer

      The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area If the scroll bar is at the very lef t or if the element is not scrollablethis number will be 0

      Example 1 Get the scrollLef t of a paragraph

      Javascript

      var p = $(pfirst) $(plast)text( scrollLeft + pscrollLeft() )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      scrollLeft

      Set the current horizontal posit ion of the scroll bar for each of the set of matched elements

      Added in version 126

      scrollLef t (value)jQuery

      valueNumber An integer indicat ing the new posit ion to set the scroll bar to

      The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area Sett ing the scrollLef t posit ions the horizontal scroll of each matchedelement

      Example 1 Set the scrollLef t of a div

      Javascript

      $(divdemo)scrollLeft(300)

      CSS

      divdemo backgroundCCCCCC none repeat scroll 0 0 border3px solid 666666 margin5px padding5px positionrelative width200px height100px overflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

      HTML

      ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

      scrollTop

      Get the current vert ical posit ion of the scroll bar for the f irst element in the set of matchedelements

      Added in version 126

      scrollTop()Integer

      The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area If the scroll bar is at the very top or if the element is not scrollable thisnumber will be 0

      Example 1 Get the scrollTop of a paragraph

      Javascript

      var p = $(pfirst)$(plast)text( scrollTop + pscrollTop() )

      CSS

      p margin10pxpadding5pxborder2px solid 666

      HTML

      ltpgtHelloltpgtltpgtltpgt

      scrollTop

      Set the current vert ical posit ion of the scroll bar for each of the set of matched elements

      Added in version 126

      scrollTop(value)jQuery

      valueNumber An integer indicat ing the new posit ion to set the scroll bar to

      The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area Sett ing the scrollTop posit ions the vert ical scroll of each matched element

      Example 1 Set the scrollTop of a div

      Javascript

      $(divdemo)scrollTop(300)

      CSS

      divdemo backgroundCCCCCC none repeat scroll 0 0border3px solid 666666margin5pxpadding5pxpositionrelativewidth200pxheight100pxoverflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

      HTML

      ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

      position

      Get the current coordinates of the f irst element in the set of matched elements relat ive to theoffset parent

      Added in version 12

      posit ion()Object

      The posit ion() method allows us to retrieve the current posit ion of an element relative to theoffset parent Contrast this with of fset() which retrieves the current posit ion relative to thedocument When posit ioning a new element near another one and within the same containingDOM element posit ion() is the more useful

      Returns an object containing the propert ies top and lef t

      Example 1 Access the posit ion of the second paragraph

      Javascript

      var p = $(pfirst)var position = pposition()$(plast)text( left + positionleft + top + positiontop )

      CSS

      div padding 15px p margin-left10px

      HTML

      ltdivgt ltpgtHelloltpgtltdivgtltpgtltpgt

      offset

      Get the current coordinates of the f irst element in the set of matched elements relat ive to thedocument

      Added in version 12

      offset()Object

      The of fset() method allows us to retrieve the current posit ion of an element relative to thedocument Contrast this with posit ion() which retrieves the current posit ion relative to the offsetparent When posit ioning a new element on top of an exist ing one for global manipulat ion (inpart icular for implement ing drag-and-drop) of fset() is the more useful

      of fset() returns an object containing the propert ies top and lef t

      Note jQuery does not support getting the offset coordinates of hidden elements oraccounting for borders margins or padding set on the body element

      Example 1 Access the of fset of the second paragraph

      Javascript

      var p = $(plast)var offset = poffset()phtml( left + offsetleft + top + offsettop )

      CSS

      p margin-left10px

      HTML

      ltpgtHelloltpgtltpgt2nd Paragraphltpgt

      Example 2 Click to see the of fset

      Javascript

      $( documentbody)cl ick(function (e) var offset = $(this)offset() estopPropagation() $(result)text(thistagName + coords ( + offsetleft + + offsettop + )))

      CSS

      p margin-left10px colorblue width200px cursorpointer span colorred cursorpointer divabs width50px height50px positionabsolute left220px top35px background-colorgreen cursorpointer

      HTML

      ltdiv id=resultgtClick an elementltdivgtltpgt This is the best way to ltspangtfindltspangt an offsetltpgt

      ltdiv class=absgtltdivgt

      offset

      Set the current coordinates of every element in the set of matched elements relat ive to thedocument

      Added in version 14

      offset(funct ion(index coords))jQuery

      funct ion(indexcoords)Funct ion

      A funct ion to return the coordinates to set Receives the index of theelement in the collect ion as the f irst argument and the currentcoordinates as the second argument The funct ion should return anobject with the new top and lef t propert ies

      The of fset() set ter method allows us to reposit ion an element The element s posit ion isspecif ied relative to the document If the element s posit ion style property is current ly stat ic it

      will be set to relat ive to allow for this reposit ioning

      Example 1 Set the of fset of the second paragraph

      Javascript

      $(plast)offset( top 10 left 30 )

      CSS

      p margin-left10px

      HTML

      ltpgtHelloltpgtltpgt2nd Paragraphltpgt

      css

      Get the value of a style property for the f irst element in the set of matched elements

      Added in version 10

      css(propertyName)String

      propertyNameString A CSS property

      The css() method is a convenient way to get a style property f rom the f irst matched elementespecially in light of the dif ferent ways browsers access most of those propert ies (thegetComputedStyle() method in standards-based browsers versus the currentStyle andrunt imeStyle propert ies in Internet Explorer) and the dif ferent terms browsers use for certainpropert ies For example Internet Explorers DOM implementat ion refers to the f loat property asstyleFloat while W3C standards-compliant browsers refer to it as cssFloat The css() methodaccounts for such dif ferences producing the same result no matter which term we use Forexample an element that is f loated lef t will return the string lef t for each of the following threelines

      1 $(divlef t )css(f loat )

      2 $(divlef t )css(cssFloat )

      3 $(divlef t )css(styleFloat )

      Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color)and css(backgroundColor) Dif ferent browsers may return CSS color values that are logicallybut not textually equal eg FFF f f f f f f and rgb(255255255)

      but not textually equal eg FFF f f f f f f and rgb(255255255)

      Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

      Example 1 To access the background color of a clicked div

      Javascript

      $(div)cl ick(function () var color = $(this)css(background-color) $(result)html(That div is ltspan style=color + color + gt + color + ltspangt))

      CSS

      div width60px height60px margin5px floatleft

      HTML

      ltspan id=resultgtampnbspltspangtltdiv style=background-colorbluegtltdivgtltdiv style=background-colorrgb(159930)gtltdivgt

      ltdiv style=background-color123456gtltdivgtltdiv style=background-colorf11gtltdivgt

      css

      Set one or more CSS propert ies for the set of matched elements

      Added in version 10

      css(map)jQuery

      mapMap A map of property-value pairs to set

      As with the prop() method the css() method makes sett ing propert ies of elements quick andeasy This method can take either a property name and value as separate parameters or asingle map of key-value pairs (JavaScript object notat ion)

      Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color

      f fe border-lef t 5px solid ccc) and css(backgroundColor f fe borderLeft 5px solidccc) Not ice that with the DOM notat ion quotat ion marks around the property names areopt ional but with CSS notat ion theyre required due to the hyphen in the name

      When using css() as a setter jQuery modif ies the element s style property For example$(mydiv)css(color green) is equivalent to documentgetElementById(mydiv)stylecolor =green Sett ing the value of a style property to an empty string acirceurordquo eg $(mydiv)css(color )acirceurordquo removes that property f rom an element if it has already been direct ly applied whether in theHTML style at t ribute through jQuerys css() method or through direct DOM manipulat ion ofthe style property It does not however remove a style that has been applied with a CSS rule ina stylesheet or ltstylegt element

      As of jQuery 16 css() accepts relat ive values similar to animate() Relat ive values are a stringstart ing with += or -= to increment or decrement the current value For example if an element spadding-lef t was 10px css( padding-lef t +=15 ) would result in a total padding-lef t of 25px

      As of jQuery 14 css() allows us to pass a funct ion as the property value

      $(divexample)css(width function(index) return index 50)

      This example sets the widths of the matched elements to incrementally larger values

      Note If nothing is returned in the setter funct ion (ie funct ion(index style)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

      Example 1 To change the color of any paragraph to red on mouseover event

      Javascript

      $(p)mouseover(function () $(this)css(colorred) )

      CSS

      p colorblue width200px font-size14px

      HTML

      ltpgtJust roll the mouse over meltpgt

      ltpgtOr me to see a color changeltpgt

      Example 2 Increase the width of box by 200 pixels

      Javascript

      $(box)one( cl ick function () $( this )css( width+=200 ) )

      CSS

      box background black color snow width100px padding10px

      HTML

      ltdiv id=boxgtClick me to growltdivgt

      Example 3 To highlight a clicked word in the paragraph

      Javascript

      var words = $(pfirst)text()split( ) var text = wordsjoin(ltspangt ltspangt) $(pfirst)html(ltspangt + text + ltspangt) $(span)cl ick(function () $(this)css(background-coloryellow) )

      CSS

      p colorblue font-weightbold cursorpointer

      HTML

      ltpgt Once upon a time there was a man who l ived in a pizza parlor This man just loved pizza and ate it al l the time He went on to be the happiest man in the world The endltpgt

      Example 4 To set the color of all paragraphs to red and background to blue

      Javascript

      $(p)hover(function () $(this)css(background-color yellow font-weight bolder) function () var cssObj = background-color ddd font-weight color rgb(040244) $(this)css(cssObj) )

      CSS

      p colorgreen

      HTML

      ltpgtMove the mouse over a paragraphltpgt ltpgtLike this one or the one aboveltpgt

      Example 5 Increase the size of a div when you click it

      Javascript

      $(div)cl ick(function() $(this)css( width function(index value) return parseFloat(value) 12 height function(index value) return parseFloat(value) 12

      ) )

      CSS

      div width 20px height 15px background-color f33

      HTML

      ltdivgtclickltdivgt ltdivgtclickltdivgt

      toggleClass see Attributes

      removeClass see Attributes

      hasClass see Attributes

      addClass see Attributes

      Manipulation

      removeProp see Attributes

      prop see Attributes

      prop see Attributes

      outerWidth see CSS

      outerHeight see CSS

      innerWidth see CSS

      innerHeight see CSS

      width see CSS

      width see CSS

      height see CSS

      height see CSS

      scrollLeft see CSS

      scrollLeft see CSS

      scrollTop see CSS

      scrollTop see CSS

      position see CSS

      offset see CSS

      offset see CSS

      css see CSS

      css see CSS

      unwrap

      Remove the parents of the set of matched elements f rom the DOM leaving the matchedelements in their place

      Added in version 14

      unwrap()jQuery

      The unwrap() method removes the element s parent This is ef fect ively the inverse of thewrap() method The matched elements (and their siblings if any) replace their parents withinthe DOM structure

      Example 1 Wrapunwrap a div around each of the paragraphs

      Javascript

      $(button)toggle(function() $(p)wrap(ltdivgtltdivgt) function() $(p)unwrap())

      CSS

      div border 2px solid blue p backgroundyellow margin4px

      HTML

      ltbuttongtwrapunwrapltbuttongtltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

      detach

      Remove the set of matched elements f rom the DOM

      Added in version 14

      detach(selector)jQuery

      selectorSelector (opt ional) A selector expression that f ilters the set of matchedelements to be removed

      The detach() method is the same as remove() except that detach() keeps all jQuery dataassociated with the removed elements This method is useful when removed elements are tobe reinserted into the DOM at a later t ime

      Example 1 Detach all paragraphs from the DOM

      Javascript

      $(p)cl ick(function() $(this)toggleClass(off) ) var p $(button)cl ick(function() i f ( p ) pappendTo(body) p = null else p = $(p)detach() )

      CSS

      p backgroundyellow margin6px 0 poff background black

      HTML

      ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtAttachdetach paragraphsltbuttongt

      clone

      Create a deep copy of the set of matched elements

      Added in version 15

      clone(withDataAndEvents deepWithDataAndEvents)jQuery

      withDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data should be copied along with the

      elements The default value is false In jQuery 150the default value was incorrectly true it was changedback to false in 151 and up

      deepWithDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data for all children of the clonedelement should be copied By default its valuematches the f irst argument s value (which defaultsto false)

      The clone() method performs a deep copy of the set of matched elements meaning that itcopies the matched elements as well as all of their descendant elements and text nodes Whenused in conjunct ion with one of the insert ion methods clone() is a convenient way to duplicateelements on a page Consider the following HTML

      ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      As shown in the discussion for append() normally when an element is inserted somewhere inthe DOM it is moved from its old locat ion So given the code

      $(hello)appendTo(goodbye)

      The result ing DOM structure would be

      ltdiv class=containergt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

      To prevent this and instead create a copy of the element you could write the following

      $(hello)clone()appendTo(goodbye)

      This would produce

      ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

      Note that when using the clone() method you can modify the cloned elements ortheir contents before (re-)inserting them into the document

      Normally any event handlers bound to the original element are not copied to the clone Theopt ional withDataAndEvents parameter allows us to change this behavior and to instead makecopies of all of the event handlers as well bound to the new copy of the element As of jQuery14 all element data (at tached by the data() method) is also copied to the new copy

      However objects and arrays within element data are not copied and will cont inue to be sharedbetween the cloned element and the original element To deep copy all data copy each onemanually

      var $elem = $(elem)data( arr [ 1 ] ) Original element with attached data $clone = $elemclone( true ) data( arr $extend( [] $elemdata(arr) ) ) Deep copy to prevent data sharing

      As of jQuery 15 withDataAndEvents can be opt ionally enhanced withdeepWithDataAndEvents to copy the events and data for all children of the cloned element

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

      Javascript

      $(b)clone()prependTo(p)

      HTML

      ltbgtHelloltbgtltpgt how are youltpgt

      Example 2 When using clone() to clone a collect ion of elements that are not at tached to theDOM their order when inserted into the DOM is not guaranteed However it may be possible topreserve sort order with a workaround as demonstrated

      CSS

      orig copy copy-correct float left width 20

      Javascript

      sort order is not guaranteed here and may vary with browser $(copy)append($(orig elem) clone() children(a) prepend(foo - ) parent() clone()) correct way to approach where order is maintained$(copy-correct) append($(orig elem) clone() children(a) prepend(bar - ) end())

      HTML

      ltdiv id=origgt ltdiv class=elemgtltagt1ltagtltdivgt ltdiv class=elemgtltagt2ltagtltdivgt ltdiv class=elemgtltagt3ltagtltdivgt ltdiv class=elemgtltagt4ltagtltdivgt ltdiv class=elemgtltagt5ltagtltdivgtltdivgtltdiv id=copygtltdivgtltdiv id=copy-correctgtltdivgt

      remove

      Remove the set of matched elements f rom the DOM

      Added in version 10

      remove(selector)jQuery

      selectorString (opt ional) A selector expression that f ilters the set of matchedelements to be removed

      Similar to empty() the remove() method takes elements out of the DOM Use remove() when

      you want to remove the element itself as well as everything inside it In addit ion to theelements themselves all bound events and jQuery data associated with the elements areremoved To remove the elements without removing data and events use detach() instead

      Consider the following HTML

      ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      We can target any element for removal

      $(hello)remove()

      This will result in a DOM structure with the ltdivgt element deleted

      ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo Other jQuery constructs such as data or event handlers are erased as well

      We can also include a selector as an opt ional parameter For example we could rewrite theprevious DOM removal code as follows

      $(div)remove(hello)

      This would result in the same DOM structure

      ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      Example 1 Removes all paragraphs from the DOM

      Javascript

      $(button)cl ick(function () $(p)remove() )

      CSS

      p backgroundyellow margin6px 0

      HTML

      ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtCall remove() on paragraphsltbuttongt

      Example 2 Removes all paragraphs that contain Hello f rom the DOM Analogous to doing$(p)f ilter(contains(Hello))remove()

      Javascript

      $(button)cl ick(function () $(p)remove(contains(Hello)) )

      CSS

      p backgroundyellow margin6px 0

      HTML

      ltp class=hellogtHelloltpgt how are ltpgtyoultpgt

      ltbuttongtCall remove(contains(Hello)) on paragraphsltbuttongt

      empty

      Remove all child nodes of the set of matched elements f rom the DOM

      Added in version 10

      empty()jQuery

      This method removes not only child (and other descendant) elements but also any text withinthe set of matched elements This is because according to the DOM specif icat ion any stringof text within an element is considered a child node of that element Consider the followingHTML

      ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      We can target any element for removal

      $(hello)empty()

      This will result in a DOM structure with the Hello text deleted

      ltdiv class=containergt ltdiv class=hellogtltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

      If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo

      To avoid memory leaks jQuery removes other constructs such as data and event handlersfrom the child elements before removing the elements themselves

      Example 1 Removes all child nodes (including text nodes) f rom all paragraphs

      Javascript

      $(button)cl ick(function () $(p)empty() )

      CSS

      p backgroundyellow

      HTML

      ltpgt Hello ltspangtPersonltspangt lta href=javascriptgtand personltagtltpgt

      ltbuttongtCall empty() on above paragraphltbuttongt

      replaceAll

      Replace each target element with the set of matched elements

      Added in version 12

      replaceAll(target)jQuery

      targetSelector A selector expression indicat ing which element(s) to replace

      The replaceAll() method is corollary to replaceWith() but with the source and target reversedConsider this DOM structure

      ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

      We can create an element then replace other elements with it

      $(lth2gtNew headinglth2gt)replaceAll( inner)

      This causes all of them to be replaced

      ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

      Or we could select an element to use as the replacement

      $(first)replaceAll( third)

      This results in the DOM structure

      ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

      From this example we can see that the selected element replaces the target by being movedfrom its old locat ion not by being cloned

      Example 1 Replace all the paragraphs with bold words

      Javascript

      $(ltbgtParagraph ltbgt)replaceAll(p) check replaceWith() examples

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      replaceWith

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

      Added in version 14

      replaceWith(funct ion)jQuery

      funct ionFunct ion A funct ion that returns content with which to replace the set ofmatched elements

      The replaceWith() method removes content f rom the DOM and inserts new content in its placewith a single call Consider this DOM structure

      ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

      The second inner ltdivgt could be replaced with the specif ied HTML

      $(divsecond)replaceWith(lth2gtNew headinglth2gt)

      This results in the structure

      ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt lth2gtNew headinglth2gt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

      All inner ltdivgt elements could be targeted at once

      $(divinner)replaceWith(lth2gtNew headinglth2gt)

      This causes all of them to be replaced

      ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

      An element could also be selected as the replacement

      $(divthird)replaceWith($(first))

      This results in the DOM structure

      ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

      This example demonstrates that the selected element replaces the target by being moved fromits old locat ion not by being cloned

      The replaceWith() method like most jQuery methods returns the jQuery object so that othermethods can be chained onto it However it must be noted that the original jQuery object isreturned This object refers to the element that has been removed from the DOM not the newelement that has replaced it

      As of jQuery 14 replaceWith() can also work on disconnected DOM nodes For example withthe following code replaceWith() returns a jQuery set containing only a paragraph

      $(ltdivgt)replaceWith(ltpgtltpgt)

      The replaceWith() method can also take a funct ion as its argument

      $(divcontainer)replaceWith(function() return $(this)contents())

      This results in ltdiv class=containergt being replaced by its three child ltdivgts The return valueof the funct ion may be an HTML string DOM element or jQuery object

      Example 1 On click replace the button with a div containing the same word

      Javascript

      $(button)cl ick(function () $(this)replaceWith( ltdivgt + $(this)text() + ltdivgt ))

      CSS

      button displayblock margin3px colorred width200px div colorred border2px solid blue width200px margin3px text-aligncenter

      HTML

      ltbuttongtFirstltbuttongtltbuttongtSecondltbuttongtltbuttongtThirdltbuttongt

      Example 2 Replace all paragraphs with bold words

      Javascript

      $(p)replaceWith( ltbgtParagraph ltbgt )

      HTML

      ltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

      Example 3 On click replace each paragraph with a div that is already in the DOM and selectedwith the $() funct ion Not ice it doesnt clone the object but rather moves it to replace theparagraph

      Javascript

      $(p)cl ick(function () $(this)replaceWith( $(div) ))

      CSS

      div border2px solid blue colorred margin3px p border2px solid red colorblue margin3px cursorpointer

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      ltdivgtReplacedltdivgt

      Example 4 On button click replace the containing div with its child divs and append the classname of the selected element to the paragraph

      Javascript

      $(button)bind(click function() var $container = $(divcontainer)replaceWith(function() return $(this)contents() )

      $(p)append( $containerattr(class) ))

      CSS

      container background-color 991 inner color 911

      HTML

      ltpgt ltbuttongtReplaceltbuttongtltpgtltdiv class=containergt ltdiv class=innergtScoobyltdivgt ltdiv class=innergtDoobyltdivgt ltdiv class=innergtDooltdivgtltdivgt

      wrapInner

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

      Added in version 14

      wrapInner(funct ion(index))jQuery

      funct ion(index)Funct ion A callback funct ion which generates a structure to wraparound the content of the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

      The wrapInner() funct ion can take any string or object that could be passed to the $() factoryfunct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element The structure will be wrapped around the content ofeach of the elements in the set of matched elements

      Consider the following HTML

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      Using wrapInner() we can insert an HTML structure around the content of each inner ltdivgtelements like so

      $(inner)wrapInner(ltdiv class=new gt)

      The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around the content of each matched element

      ltdiv class=containergt ltdiv class=innergt ltdiv class=newgtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=newgtGoodbyeltdivgt ltdivgtltdivgt

      The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the content of the correspondingelement For example

      $(inner)wrapInner(function() return ltdiv class= + thisnodeValue + gt)

      This will cause each ltdivgt to have a class corresponding to the text it wraps

      ltdiv class=containergt ltdiv class=innergt ltdiv class=HellogtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=GoodbyegtGoodbyeltdivgt ltdivgtltdivgt

      Note When passing a selector string to the wrapInner() funct ion the expected input is wellformed HTML with correct ly closed tags Examples of valid input include

      $(elem)wrapInner(ltdiv class=test gt)$(elem)wrapInner(ltdiv class=testgtltdivgt)$(elem)wrapInner(ltdiv class=testgtltdivgt)

      Example 1 Selects all paragraphs and wraps a bold tag around each of its contents

      Javascript

      $(p)wrapInner(ltbgtltbgt)

      CSS

      p backgroundbbf

      HTML

      ltpgtHelloltpgt

      ltpgtcruelltpgt ltpgtWorldltpgt

      Example 2 Wraps a newly created tree of objects around the inside of the body

      Javascript

      $(body)wrapInner(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

      CSS

      div border2px green solid margin2px padding2px p backgroundyellow margin2px padding2px

      HTML

      Plain old text or is it

      Example 3 Selects all paragraphs and wraps a bold tag around each of its contents

      Javascript

      $(p)wrapInner(documentcreateElement(b))

      CSS

      p background9f9

      HTML

      ltpgtHelloltpgt

      ltpgtcruelltpgt ltpgtWorldltpgt

      Example 4 Selects all paragraphs and wraps a jQuery object around each of its contents

      Javascript

      $(p)wrapInner($(ltspan class=redgtltspangt))

      CSS

      p background9f9 red colorred

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      wrapAll

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

      Added in version 12

      wrapAll(wrappingElement)jQuery

      wrappingElementStringSelector ElementjQuery

      An HTML snippet selector expression jQuery object or DOMelement specifying the structure to wrap around the matchedelements

      The wrapAll() funct ion can take any string or object that could be passed to the $() funct ion tospecify a DOM structure This structure may be nested several levels deep but should containonly one inmost element The structure will be wrapped around all of the elements in the set ofmatched elements as a single group

      Consider the following HTML

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      Using wrapAll() we can insert an HTML structure around the inner ltdivgt elements like so

      $(inner)wrapAll(ltdiv class=new gt)

      The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around all matched elements

      ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

      Example 1 Wrap a new div around all of the paragraphs

      Javascript

      $(p)wrapAll(ltdivgtltdivgt)

      CSS

      div border 2px solid blue p backgroundyellow margin4px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

      Javascript

      $(span)wrapAll(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

      CSS

      div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

      HTML

      ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

      Example 3 Wrap a new div around all of the paragraphs

      Javascript

      $(p)wrapAll(documentcreateElement(div))

      CSS

      div border 2px solid blue p backgroundyellow margin4px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

      Javascript

      $(p)wrapAll($(doublediv))

      CSS

      div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

      wrap

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

      Added in version 14

      wrap(funct ion(index))jQuery

      funct ion(index)Funct ion A callback funct ion returning the HTML content or jQueryobject to wrap around the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

      The wrap() funct ion can take any string or object that could be passed to the $() factory

      funct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element A copy of this structure will be wrapped around eachof the elements in the set of matched elements This method returns the original set ofelements for chaining purposes

      Consider the following HTML

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      Using wrap() we can insert an HTML structure around the inner ltdivgt elements like so

      $(inner)wrap(ltdiv class=new gt)

      The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around each matched element

      ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=newgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

      The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the corresponding element Forexample

      $(inner)wrap(function() return ltdiv class= + $(this)text() + gt)

      This will cause each ltdivgt to have a class corresponding to the text it wraps

      ltdiv class=containergt ltdiv class=Hellogt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=Goodbyegt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

      Example 1 Wrap a new div around all of the paragraphs

      Javascript

      $(p)wrap(ltdivgtltdivgt)

      CSS

      div border 2px solid blue p backgroundyellow margin4px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

      Javascript

      $(span)wrap(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

      CSS

      div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

      HTML

      ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

      Example 3 Wrap a new div around all of the paragraphs

      Javascript

      $(p)wrap(documentcreateElement(div))

      CSS

      div border 2px solid blue p backgroundyellow margin4px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

      Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

      Javascript

      $(p)wrap($(doublediv))

      CSS

      div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

      HTML

      ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

      insertBefore

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

      Added in version 10

      insertBefore(target)jQuery

      targetSelectorElementjQuery

      A selector element HTML string or jQuery object the matched set ofelements will be inserted before the element(s) specif ied by thisparameter

      The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

      Consider the following HTML

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      We can create content and insert it before several elements at once

      $(ltpgtTestltpgt)insertBefore(inner)

      Each inner ltdivgt element gets this new content

      ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Example 1 Inserts all paragraphs before an element with id of foo Same as$( foo)before(p)

      Javascript

      $(p)insertBefore(foo) check before() examples

      CSS

      foo backgroundyellow

      HTML

      ltdiv id=foogtFOOltdivgtltpgtI would l ike to say ltpgt

      before

      Insert content specif ied by the parameter before each element in the set of matchedelements

      Added in version 14

      before(funct ion)jQuery

      funct ionFunct ion A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert before each element in the set of matched elementsReceives the index posit ion of the element in the set as anargument Within the funct ion this refers to the current element inthe set

      The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

      Consider the following HTML

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      You can create content and insert it before several elements at once

      $(inner)before(ltpgtTestltpgt)

      Each inner ltdivgt element gets this new content

      ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      In jQuery 14 before() and af ter() will also work on disconnected DOM nodes

      $(ltdivgt)before(ltpgtltpgt)

      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 prepend() and af ter() before() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

      For example the following will insert two new ltdivgts and an exist ing ltdivgt before the f irstparagraph

      var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

      $(p)first()before($newdiv1 [newdiv2 existingdiv1])

      Since before() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so$(p)f irst()before($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

      Example 1 Inserts some HTML before all paragraphs

      Javascript

      $(p)before(ltbgtHelloltbgt)

      CSS

      p backgroundyellow

      HTML

      ltpgt is what I saidltpgt

      Example 2 Inserts a DOM element before all paragraphs

      Javascript

      $(p)before( documentcreateTextNode(Hello) )

      CSS

      p backgroundyellow

      HTML

      ltpgt is what I saidltpgt

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

      Javascript

      $(p)before( $(b) )

      CSS

      p backgroundyellow

      HTML

      ltpgt is what I saidltpgtltbgtHelloltbgt

      insertAfter

      Insert every element in the set of matched elements af ter the target

      Added in version 10

      insertAfter(target)jQuery

      targetSelectorElementjQuery

      A selector element HTML string or jQuery object the matched set ofelements will be inserted af ter the element(s) specif ied by thisparameter

      The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

      Consider the following HTML

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      We can create content and insert it af ter several elements at once

      $(ltpgtTestltpgt)insertAfter( inner)

      Each inner ltdivgt element gets this new content

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

      We can also select an element on the page and insert it af ter another

      $(h2)insertAfter($(container))

      If an element selected this way is inserted elsewhere it will be moved af ter the target (notcloned)

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Example 1 Inserts all paragraphs af ter an element with id of foo Same as $( foo)af ter(p)

      Javascript

      $(p)insertAfter(foo) check after() examples

      CSS

      foo backgroundyellow

      HTML

      ltpgt is what I said ltpgtltdiv id=foogtFOOltdivgt

      after

      Insert content specif ied by the parameter af ter each element in the set of matched elements

      Added in version 14

      after(funct ion(index))jQuery

      funct ion(index)Funct ion A funct ion that returns an HTML string DOM element(s) orjQuery object to insert af ter each element in the set ofmatched elements Receives the index posit ion of theelement in the set as an argument Within the funct ion thisrefers to the current element in the set

      The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

      Using the following HTML

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      Content can be created and then inserted af ter several elements at once

      $(inner)after(ltpgtTestltpgt)

      Each inner ltdivgt element gets this new content

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

      An element in the DOM can also be selected and inserted af ter another element

      $(container)after($(h2))

      If an element selected this way is inserted elsewhere it will be moved rather than cloned

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Inserting Disconnected DOM nodes

      As of jQuery 14 before() and af ter() will also work on disconnected DOM nodes For examplegiven the following code

      $(ltdivgt)after(ltpgtltpgt)

      The result is a jQuery set containing a div and a paragraph in that order That set can befurther manipulated even before it is inserted in the document

      $(ltdivgt)after(ltpgtltpgt)addClass(foo) fi lter(p)attr( id bar)html(hello)end()appendTo(body)

      This results in the following elements inserted just before the closing ltbodygt tag

      ltdiv class=foogtltdivgtltp class=foo id=bargthelloltpgt

      Passing a Function

      As of jQuery 14 af ter() supports passing a funct ion that returns the elements to insert

      $(p)after(function() return ltdivgt + thisclassName + ltdivgt)

      This example inserts a ltdivgt af ter each paragraph with each new ltdivgt containing the class

      name(s) of its preceding paragraph

      Additional Arguments

      Similar to other content-adding methods such as prepend() and before() af ter() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

      For example the following will insert two new ltdivgts and an exist ing ltdivgt af ter the f irstparagraph

      var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

      $(p)first()after($newdiv1 [newdiv2 existingdiv1])

      Since af ter() can accept any number of addit ional arguments the same result can be achievedby passing in the three ltdivgts as three separate arguments like so $(p)f irst()af ter($newdiv1newdiv2 exist ingdiv1) The type and number of arguments will largely depend on the elementsare collected in the code

      Example 1 Inserts some HTML after all paragraphs

      Javascript

      $(p)after(ltbgtHelloltbgt)

      CSS

      p backgroundyellow

      HTML

      ltpgtI would l ike to say ltpgt

      Example 2 Inserts a DOM element af ter all paragraphs

      Javascript

      $(p)after( documentcreateTextNode(Hello) )

      CSS

      p backgroundyellow

      HTML

      ltpgtI would l ike to say ltpgt

      Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) af ter all paragraphs

      Javascript

      $(p)after( $(b) )

      CSS

      p backgroundyellow

      HTML

      ltbgtHelloltbgtltpgtI would l ike to say ltpgt

      prependTo

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

      Added in version 10

      prependTo(target)jQuery

      targetSelectorElementjQuery

      A selector element HTML string or jQuery object the matched set ofelements will be inserted at the beginning of the element(s) specif iedby this parameter

      The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

      Consider the following HTML

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      We can create content and insert it into several elements at once

      $(ltpgtTestltpgt)prependTo(inner)

      Each inner ltdivgt element gets this new content

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

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

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Example 1 Prepends all spans to the element with the ID foo

      CSS

      div backgroundyellow

      Javascript

      $(span)prependTo(foo) check prepend() examples

      HTML

      ltdiv id=foogtFOOltdivgt

      ltspangtI have something to say ltspangt

      prepend

      Insert content specif ied by the parameter to the beginning of each element in the set ofmatched elements

      Added in version 14

      prepend(funct ion(index html))jQuery

      funct ion(indexhtml)Funct ion

      A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the beginning of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

      The prepend() method inserts the specif ied content as the f irst child of each element in thejQuery collect ion (To insert it as the last child use append())

      The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

      Consider the following HTML

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      You can create content and insert it into several elements at once

      $(inner)prepend(ltpgtTestltpgt)

      Each ltdiv class=innergt element gets this new content

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

      You can also select an element on the page and insert it into another

      $(container)prepend($(h2))

      If a single element selected this way is inserted elsewhere it will be moved into the target (notcloned)

      ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      Important If there is more than one target element however cloned copies of the insertedelement will be created for each target af ter the f irst

      Additional Arguments

      Similar to other content-adding methods such as append() and before() prepend() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

      For example the following will insert two new ltdivgts and an exist ing ltdivgt as the f irst threechild nodes of the body

      var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

      $(body)prepend($newdiv1 [newdiv2 existingdiv1])

      Since prepend() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

      $(body)prepend($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

      Example 1 Prepends some HTML to all paragraphs

      Javascript

      $(p)prepend(ltbgtHello ltbgt)

      CSS

      p backgroundyellow

      HTML

      ltpgtthere friendltpgt

      ltpgtamigoltpgt

      Example 2 Prepends a DOM Element to all paragraphs

      Javascript

      $(p)prepend(documentcreateTextNode(Hello ))

      CSS

      p backgroundyellow

      HTML

      ltpgtis what Id sayltpgtltpgtis what I saidltpgt

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

      Javascript

      $(p)prepend( $(b) )

      CSS

      p backgroundyellow

      HTML

      ltpgt is what was saidltpgtltbgtHelloltbgt

      appendTo

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

      Added in version 10

      appendTo(target)jQuery

      targetSelectorElementjQuery

      A selector element HTML string or jQuery object the matched set ofelements will be inserted at the end of the element(s) specif ied by thisparameter

      The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

      Consider the following HTML

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      We can create content and insert it into several elements at once

      $(ltpgtTestltpgt)appendTo(inner)

      Each inner ltdivgt element gets this new content

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Example 1 Appends all spans to the element with the ID foo

      Javascript

      $(span)appendTo(foo) check append() examples

      CSS

      foo backgroundyellow

      HTML

      ltspangtI have nothing more to say ltspangt

      ltdiv id=foogtFOO ltdivgt

      append

      Insert content specif ied by the parameter to the end of each element in the set of matchedelements

      Added in version 14

      append(funct ion(index html))jQuery

      funct ion(indexhtml)Funct ion

      A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the end of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

      The append() method inserts the specif ied content as the last child of each element in thejQuery collect ion (To insert it as the first child use prepend())

      The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

      Consider the following HTML

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

      You can create content and insert it into several elements at once

      $(inner)append(ltpgtTestltpgt)

      Each inner ltdivgt element gets this new content

      lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

      ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

      If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

      Additional Arguments

      Similar to other content-adding methods such as prepend() and before() append() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

      For example the following will insert two new ltdivgts and an exist ing ltdivgt as the last threechild nodes of the body

      var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

      $(body)append($newdiv1 [newdiv2 existingdiv1])

      Since append() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

      $(body)append($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

      Example 1 Appends some HTML to all paragraphs

      Javascript

      $(p)append(ltstronggtHelloltstronggt)

      CSS

      p backgroundyellow

      HTML

      ltpgtI would l ike to say ltpgt

      Example 2 Appends an Element to all paragraphs

      Javascript

      $(p)append(documentcreateTextNode(Hello))

      CSS

      p backgroundyellow

      HTML

      ltpgtI would l ike to say ltpgt

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

      Javascript

      $(p)append( $(strong) )

      CSS

      p backgroundyellow

      HTML

      ltstronggtHello worldltstronggtltpgtI would l ike to say ltpgt

      val see Attributes

      val see Attributes

      text

      Get the combined text contents of each element in the set of matched elements includingtheir descendants

      Added in version 10

      text()String

      Unlike the html() method text() can be used in both XML and HTML documents The result ofthe text() method is a string containing the combined text of all matched elements (Due tovariat ions in the HTML parsers in dif ferent browsers the text returned may vary in newlines andother white space) Consider the following HTML

      ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgt ltdivgt

      The code $(divdemo-container)text() would produce the following result

      Demonstrat ion Box list item 1 list item 2

      The text() method cannot be used on form inputs or scripts To set or get the text value ofinput or textarea elements use the val() method To get the value of a script element use thehtml() method

      As of jQuery 14 the text() method returns the value of text and CDATA nodes as well aselement nodes

      Example 1 Find the text in the f irst paragraph (stripping out the html) then set the html of thelast paragraph to show it is just text (the red bold is gone)

      Javascript

      var str = $(pfirst)text() $(plast)html(str)

      CSS

      p colorblue margin8px b colorred

      HTML

      ltpgtltbgtTestltbgt Paragraphltpgt

      ltpgtltpgt

      text

      Set the content of each element in the set of matched elements to the specif ied text

      Added in version 14

      text(funct ion(index text))jQuery

      funct ion(indextext)Funct ion

      A funct ion returning the text content to set Receives the indexposit ion of the element in the set and the old text value as arguments

      Unlike the html() method text() 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 willrender correct ly in HTML To do so it calls the DOM method createTextNode() which replacesspecial characters with their HTML ent ity equivalents (such as amplt for lt) Consider the followingHTML

      ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgtltdivgt

      The code $(divdemo-container)text(ltpgtThis is a test ltpgt) will produce the following DOMoutput

      ltdiv class=demo-containergtampltpampgtThis is a testampltpampgtltdivgt

      It will appear on a rendered page as though the tags were exposed like this

      ltpgtThis is a testltpgt

      The text() method cannot be used on input elements For input f ield text use the val() method

      As of jQuery 14 the text() method allows us to set the text content by passing in a funct ion

      $(ul l i )text(function(index) return item number + (index + 1))

      Given an unordered list with three ltligt elements this example will produce the following DOMoutput

      ltulgt ltligtitem number 1ltligt ltligtitem number 2ltligt ltligtitem number 3ltligtltulgt

      Example 1 Add text to the paragraph (not ice the bold tag is escaped)

      Javascript

      $(p)text(ltbgtSomeltbgt new text)

      CSS

      p colorblue margin8px

      HTML

      ltpgtTest Paragraphltpgt

      html see Attributes

      html see Attributes

      toggleClass see Attributes

      removeClass see Attributes

      hasClass see Attributes

      removeAttr see Attributes

      attr see Attributes

      attr see Attributes

      addClass see Attributes

      Data

      jQueryhasData

      Determine whether an element has any jQuery data associated with it

      Added in version 15

      jQueryhasData(element)Boolean

      elementElement A DOM element to be checked for data

      The jQueryhasData() method provides a way to determine if an element current ly has anyvalues that were set using jQuerydata() If no data is associated with an element (there is nodata object at all or the data object is empty) the method returns false otherwise it returnstrue

      The primary advantage of jQueryhasData(element) is that it does not create and associate adata object with the element if none current ly exists In contrast jQuerydata(element) alwaysreturns a data object to the caller creat ing one if no data object previously existed

      Example 1 Set data on an element and see the results of hasData

      Javascript

      $(function() var $p = jQuery(p) p = $p[0] $pappend(jQueryhasData(p)+ ) false jQuerydata(p testing 123) $pappend(jQueryhasData(p)+ ) true jQueryremoveData(p testing) $pappend(jQueryhasData(p)+ ) false )

      HTML

      ltpgtResults ltpgt

      jQueryremoveData

      Remove a previously-stored piece of data

      Added in version 123

      jQueryremoveData(element name)jQuery

      elementElement A DOM element f rom which to remove data

      nameString (opt ional) A string naming the piece of data to remove

      Note This is a low-level method you should probably use removeData() instead

      The jQueryremoveData() method allows us to remove values that were previously set usingjQuerydata() When called with the name of a key jQueryremoveData() deletes that part icularvalue when called with no arguments all values are removed

      Example 1 Set a data store for 2 names then remove one of them

      Javascript

      var div = $(div)[0]$(spaneq(0))text( + $(div)data(test1))jQuerydata(div test1 VALUE-1)jQuerydata(div test2 VALUE-2)$(spaneq(1))text( + jQuerydata(div test1))jQueryremoveData(div test1)$(spaneq(2))text( + jQuerydata(div test1))$(spaneq(3))text( + jQuerydata(div test2))

      CSS

      div margin2px colorblue span colorred

      HTML

      ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt ltdivgtvalue2 after removal ltspangtltspangtltdivgt

      jQuerydata

      Store arbit rary data associated with the specif ied element Returns the value that was set

      Added in version 123

      jQuerydata(element key value)Object

      elementElement The DOM element to associate with the data

      keyString A string naming the piece of data to set

      valueObject The new data value

      Note This is a low-level method a more convenient data() is also available

      The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f ree from memory leaks jQuery ensures that thedata is removed when DOM elements are removed via jQuery methods and when the userleaves the page We can set several dist inct values for a single element and retrieve them later

      jQuerydata(documentbody foo 52)jQuerydata(documentbody bar test)

      Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

      Example 1 Store then retrieve a value from the div element

      Javascript

      var div = $(div)[0] jQuerydata(div test first 16 last pizza ) $(spanfirst)text(jQuerydata(div test)first) $(spanlast)text(jQuerydata(div test)last)

      CSS

      div colorblue span colorred

      HTML

      ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

      jQuerydata

      Returns value at named data store for the element as set by jQuerydata(element namevalue) or the full data store for the element

      Added in version 14

      jQuerydata(element)Object

      elementElement The DOM element to query for the data

      Note This is a low-level method a more convenient data() is also available

      Regarding HTML5 data- at t ributes This low-level method does NOT retrieve the data-at t ributes unless the more convenient data() method has already retrieved them

      The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f rom memory leaks We can retrieve severaldist inct values for a single element one at a t ime or as a set

      alert(jQuerydata( documentbody foo ))alert(jQuerydata( documentbody ))

      The above lines alert the data values that were set on the body element If nothing was set onthat element an empty string is returned

      Calling jQuerydata(element) retrieves all of the element s associated values as a JavaScriptobject Note that jQuery itself uses this method to store data for internal use such as eventhandlers so do not assume that it contains only data that your own code has stored

      Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

      Example 1 Get the data named blah stored at for an element

      Javascript

      $(button)cl ick(function(e) var value div = $(div)[0]

      switch ($(button)index(this)) case 0 value = jQuerydata(div blah) break case 1 jQuerydata(div blah hello) value = Stored break case 2 jQuerydata(div blah 86) value = Stored break case 3 jQueryremoveData(div blah) value = Removed break

      $(span)text( + value))

      CSS

      div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

      HTML

      ltdivgtA divltdivgtltbuttongtGet blah from the divltbuttongtltbuttongtSet blah to helloltbuttongt

      ltbuttongtSet blah to 86ltbuttongtltbuttongtRemove blah from the divltbuttongtltpgtThe blah value of this div is ltspangtltspangtltpgt

      jQuerydequeue

      Execute the next funct ion on the queue for the matched element

      Added in version 13

      jQuerydequeue(element queueName)jQuery

      elementElement A DOM element f rom which to remove and execute a queuedfunct ion

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      Note This is a low-level method you should probably use dequeue() instead

      When jQuerydequeue() is called the next funct ion on the queue is removed from the queueand then executed This funct ion should in turn (direct ly or indirect ly) cause jQuerydequeue() tobe called so that the sequence can cont inue

      Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

      Javascript

      $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $dequeue( this ) ) $(div)animate(left10px top30px 700) )

      CSS

      div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

      HTML

      ltbuttongtStartltbuttongt ltdivgtltdivgt

      jQueryqueue

      Show the queue of funct ions to be executed on the matched element

      Added in version 13

      jQueryqueue(element queueName)Array

      elementElement A DOM element to inspect for an at tached queue

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      Note This is a low-level method you should probably use queue() instead

      Example 1 Show the length of the queue

      Javascript

      $(show)cl ick(function () var n = jQueryqueue( $(div)[0] fx ) $(span)text(Queue length is + nlength) ) function runIt() $(div)show(slow) $(div)animate(left+=2002000) $(div)sl ideToggle(1000) $(div)sl ideToggle(fast) $(div)animate(left-=2001500) $(div)hide(slow) $(div)show(1200) $(div)sl ideUp(normal runIt) runIt()

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue span colorred

      HTML

      ltbutton id=showgtShow Length of Queueltbuttongt ltspangtltspangt ltdivgtltdivgt

      jQueryqueue

      Manipulate the queue of funct ions to be executed on the matched element

      Added in version 13

      jQueryqueue(element queueName callback())jQuery

      elementElement A DOM element on which to add a queued funct ion

      queueNameString A string containing the name of the queue Defaults to fx thestandard ef fects queue

      callback()Funct ion The new funct ion to add to the queue

      Note This is a low-level method you should probably use queue() instead

      Every element can have one or more queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion

      The jQueryqueue() method allows us to direct ly manipulate this queue of funct ions CallingjQueryqueue() with a callback is part icularly useful it allows us to place a new funct ion at theend of the queue

      Note that when adding a funct ion with jQueryqueue() we should ensure that jQuerydequeue()is eventually called so that the next funct ion in line executes

      Example 1 Queue a custom funct ion

      Javascript

      $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=200500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() )

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

      HTML

      Click here ltdivgtltdivgt

      Example 2 Set a queue array to delete the queue

      Javascript

      $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=2001500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() ) $(stop)cl ick(function () jQueryqueue( $(div)[0] fx [] ) $(div)stop() )

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

      HTML

      ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

      clearQueue

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

      Added in version 14

      clearQueue(queueName)jQuery

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      When the clearQueue() method is called all funct ions on the queue that have not beenexecuted are removed from the queue When used without an argument clearQueue()removes the remaining funct ions from fx the standard ef fects queue In this way it is similar tostop(true) However while the stop() method is meant to be used only with animat ionsclearQueue() can also be used to remove any funct ion that has been added to a genericjQuery queue with the queue() method

      Example 1 Empty the queue

      Javascript

      $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp())$(stop)cl ick(function () $(div)clearQueue() $(div)stop())

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

      HTML

      ltbutton id=startgtStartltbuttongtltbutton id=stopgtStopltbuttongtltdivgtltdivgt

      removeData

      Remove a previously-stored piece of data

      Added in version 123

      removeData(name)jQuery

      nameString (opt ional) A string naming the piece of data to delete

      The removeData() method allows us to remove values that were previously set using data()When called with the name of a key removeData() deletes that part icular value when calledwith no arguments all values are removed

      NOTE Start ing with jQuery 143 calling removeData() will cause the value of the propertybeing removed to revert to the value of the data at t ribute of the same name in the DOM ratherthan being set to undef ined

      Example 1 Set a data store for 2 names then remove one of them

      Javascript

      $(spaneq(0))text( + $(div)data(test1)) $(div)data(test1 VALUE-1) $(div)data(test2 VALUE-2) $(spaneq(1))text( + $(div)data(test1)) $(div)removeData(test1) $(spaneq(2))text( + $(div)data(test1)) $(spaneq(3))text( + $(div)data(test2))

      CSS

      div margin2px colorblue span colorred

      HTML

      ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt

      ltdivgtvalue2 after removal ltspangtltspangtltdivgt

      data

      Store arbit rary data associated with the matched elements

      Added in version 143

      data(obj)jQuery

      objObject An object of key-value pairs of data to update

      The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks

      We can set several dist inct 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 143 sett ing an element s data object with data(obj) extends the data previouslystored with that element jQuery itself uses the data() method to save informat ion under thenames events and handle and also reserves any data name start ing with an underscore (_)for internal use

      Prior to jQuery 143 (start ing in jQuery 14) the data() method completely replaced all datainstead of just extending the data object If you are using third-party plugins it may not beadvisable to completely replace the element s data object since plugins may have also setdata

      Due to the way browsers interact with plugins and external code the data() method cannot beused on ltobjectgt (unless it s a Flash plugin) ltappletgt or ltembedgt elements

      Example 1 Store then retrieve a value from the div element

      Javascript

      $(div)data(test first 16 last pizza )$(spanfirst)text($(div)data(test)first)$(spanlast)text($(div)data(test)last)

      CSS

      div colorblue span colorred

      HTML

      ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

      data

      Returns value at named data store for the f irst element in the jQuery collect ion as set bydata(name value)

      Added in version 14

      data()Object

      The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks We can retrieve several dist inctvalues for a single element one at a t ime or as a set

      alert($(body)data(foo))alert($(body)data())

      The above lines alert the data values that were set on the body element If no data at all wasset on that element undef ined is returned

      alert( $(body)data(foo)) undefined$(body)data(bar foobar)alert( $(body)data(foobar)) foobar

      HTML 5 data- Attributes

      As of jQuery 143 HTML 5 data- at t ributes will be automat ically pulled in to jQuerys data object The treatment of at t ributes with embedded dashes was changed in jQuery 16 to conform tothe W3C HTML5 specif icat ion

      For example given the following HTML

      ltdiv data-role=page data-last-value=43 data-hidden=true data-options=nameJohngtltdivgt

      All of the following jQuery code will work

      $(div)data(role) === page$(div)data(lastValue) === 43$(div)data(hidden) === true$(div)data(options)name === John

      Every at tempt is made to convert the string to a JavaScript value (this includes booleansnumbers objects arrays and null) otherwise it is lef t as a string To retrieve the valuesat t ribute as a string without any at tempt to convert it use the at t r() method When the dataattribute is an object (starts with ) or array (starts with [) then jQueryparseJSON is used toparse the string it must follow valid JSON syntax including quoted property names The data-at t ributes are pulled in the f irst t ime the data property is accessed and then are no longeraccessed or mutated (all data values are then stored internally in jQuery)

      Calling data() with no parameters retrieves all of the values as a JavaScript object This objectcan be safely cached in a variable as long as a new object is not set with data(obj) Using theobject direct ly to get or set values is faster than making individual calls to data() to get or seteach value

      var mydata = $(mydiv)data()if ( mydatacount lt 9 ) mydatacount = 43 mydatastatus = embiggened

      Example 1 Get the data named blah stored at for an element

      Javascript

      $(button)cl ick(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))

      CSS

      div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

      HTML

      ltdivgtA divltdivgt ltbuttongtGet blah from the divltbuttongt ltbuttongtSet blah to helloltbuttongt

      ltbuttongtSet blah to 86ltbuttongt ltbuttongtRemove blah from the divltbuttongt ltpgtThe blah value of this div is ltspangtltspangtltpgt

      dequeue

      Execute the next funct ion on the queue for the matched elements

      Added in version 12

      dequeue(queueName)jQuery

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      When dequeue() is called the next funct ion on the queue is removed from the queue and thenexecuted This funct ion should in turn (direct ly or indirect ly) cause dequeue() to be called sothat the sequence can cont inue

      Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

      Javascript

      $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $(this)dequeue() ) $(div)animate(left10px top30px 700))

      CSS

      div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

      HTML

      ltbuttongtStartltbuttongt ltdivgtltdivgt

      queue

      Show the queue of funct ions to be executed on the matched elements

      Added in version 12

      queue(queueName)Array

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      Example 1 Show the length of the queue

      Javascript

      var div = $(div)

      function runIt() divshow(slow) divanimate(left+=2002000) divsl ideToggle(1000) divsl ideToggle(fast) divanimate(left-=2001500) divhide(slow) divshow(1200) divsl ideUp(normal runIt)

      function showIt() var n = divqueue(fx) $(span)text( nlength ) setTimeout(showIt 100)

      runIt()showIt()

      CSS

      div margin3px width40px height40px positionabsolute left0px top60px backgroundgreen displaynone divnewcolor backgroundblue p colorred

      HTML

      ltpgtThe queue length is ltspangtltspangtltpgt ltdivgtltdivgt

      queue

      Manipulate the queue of funct ions to be executed on the matched elements

      Added in version 12

      queue(queueName callback( next ))jQuery

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      callback( next)Funct ion

      The new funct ion to add to the queue with a funct ion to call thatwill dequeue the next item

      Every element can have one to many queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion The typical exampleof this is calling mult iple animat ion methods on an element For example

      $(foo)sl ideUp()fadeIn()

      When this statement is executed the element begins its sliding animat ion immediately but thefading transit ion is placed on the fx queue to be called only once the sliding transit ion iscomplete

      The queue() method allows us to direct ly manipulate this queue of funct ions Calling queue()with a callback is part icularly useful it allows us to place a new funct ion at the end of thequeue

      This feature is similar to providing a callback funct ion with an animat ion method but does notrequire the callback to be given at the t ime the animat ion is performed

      $(foo)sl ideUp()$(foo)queue(function() alert(Animation complete) $(this)dequeue())

      This is equivalent to

      $(foo)sl ideUp(function() alert(Animation complete))

      Note that when adding a funct ion with queue() we should ensure that dequeue() is eventuallycalled so that the next funct ion in line executes

      In jQuery 14 the funct ion that s called is passed in another funct ion as the f irst argument thatwhen called automat ically dequeues the next item and keeps the queue moving You would useit like so

      $(test)queue(function(next) Do some stuff next())

      Example 1 Queue a custom funct ion

      Javascript

      $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=200500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() )

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

      HTML

      Click here ltdivgtltdivgt

      Example 2 Set a queue array to delete the queue

      Javascript

      $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() ) $(stop)cl ick(function () $(div)queue(fx []) $(div)stop() )

      CSS

      div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

      HTML

      ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

      Forms

      submit

      Bind an event handler to the submit JavaScript event or t rigger that event on an element

      Added in version 10

      submit()jQuery

      This method is a shortcut for bind(submit handler) in the f irst variat ion and t rigger(submit ) inthe third

      The submit event is sent to an element when the user is at tempt ing to submit a form It canonly be at tached to ltformgt elements Forms can be submit ted either by clicking an explicitltinput type=submitgt ltinput type=imagegt or ltbutton type=submitgt or by pressing

      Enter when certain form elements have focus

      Depending on the browser the Enter key may only cause a form submission if theform has exactly one text field or only when there is a submit button present Theinterface should not rely on a particular behavior for this key unless the issue isforced by observing the keypress event for presses of the Enter key

      For example consider the HTML

      ltform id=target action=destinationhtmlgt ltinput type=text value=Hello there gt ltinput type=submit value=Go gtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the form

      $(target)submit(function() alert(Handler for submit() called) return false)

      Now when the form is submit ted the message is alerted This happens prior to the actualsubmission so we can cancel the submit act ion by calling preventDefault () on the event objector by returning false f rom our handler We can trigger the event manually when another elementis clicked

      $(other)cl ick(function() $(target)submit())

      After this code executes clicks on Trigger the handler will also display the message In addit ionthe default submit act ion on the form will be f ired so the form will be submit ted

      The JavaScript submit event does not bubble in Internet Explorer However scripts that rely onevent delegat ion with the submit event will work consistent ly across browsers as of jQuery 14which has normalized the event s behavior

      Example 1 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

      Javascript

      $(form)submit(function() i f ($(inputfirst)val() == correct) $(span)text(Validated)show() return true $(span)text(Not valid)show()fadeOut(1000) return false )

      CSS

      p margin0 colorblue divp margin-left10px span colorred

      HTML

      ltpgtType correct to validateltpgt ltform action=javascriptalert(success)gt ltdivgt ltinput type=text gt

      ltinput type=submit gt ltdivgt ltformgt ltspangtltspangt

      Example 2 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

      Javascript

      $(form)submit( function () return thissome_flag_variable )

      Example 3 To trigger the submit event on the f irst form on the page t ry

      Javascript

      $(formfirst)submit()

      select

      Bind an event handler to the select JavaScript event or t rigger that event on an element

      Added in version 10

      select()jQuery

      This method is a shortcut for bind(select handler) in the f irst two variat ions andtrigger(select ) in the third

      The select event is sent to an element when the user makes a text select ion inside it Thisevent is limited to ltinput type=textgt f ields and lttextareagt boxes

      For example consider the HTML

      ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the text input

      $(target)select(function() alert(Handler for select() called))

      Now when any port ion of the text is selected the alert is displayed Merely set t ing the locat ionof the insert ion point will not t rigger the event To trigger the event manually apply select()without an argument

      $(other)cl ick(function() $(target)select())

      After this code executes clicks on the Trigger button will also alert the message

      Handler for select() called

      In addit ion the default select act ion on the f ield will be f ired so the ent ire text f ield will beselected

      The method for retrieving the current selected text differs from one browser toanother A number of jQuery plug-ins offer cross-platform solutions

      Example 1 To do something when text in input boxes is selected

      Javascript

      $(input)select( function () $(div)text(Something was selected)show()fadeOut(1000) )

      CSS

      p colorblue div colorred

      HTML

      ltpgt

      Click and drag the mouse to select text in the inputs ltpgt ltinput type=text value=Some text gt ltinput type=text value=to test on gt

      ltdivgtltdivgt

      Example 2 To trigger the select event on all input elements t ry

      Javascript

      $(input)select()

      change

      Bind an event handler to the change JavaScript event or t rigger that event on an element

      Added in version 10

      change()jQuery

      This method is a shortcut for bind(change handler) in the f irst two variat ions andtrigger(change) in the third

      The change event is sent to an element when its value changes This event is limited to ltinputgtelements lttextareagt boxes and ltselectgt elements For select boxes checkboxes and radiobuttons the event is f ired immediately when the user makes a select ion with the mouse butfor the other element types the event is deferred unt il the element loses focus

      For example consider the HTML

      ltformgt ltinput class=target type=text value=Field 1 gt ltselect class=targetgt ltoption value=option1 selected=selectedgtOption 1ltoptiongt ltoption value=option2gtOption 2ltoptiongt ltselectgtltformgtltdiv id=othergt Trigger the handlerltdivgt

      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 opt ion is selected from the dropdown the alert is displayed It is alsodisplayed if you change the text in the f ield and then click away If the f ield loses focus withoutthe contents having changed though the event is not t riggered To trigger the event manuallyapply change() without arguments

      $(other)cl ick(function() $( target)change())

      After this code executes clicks on Trigger the handler will also alert the message The messagewill display twice because the handler has been bound to the change event on both of theform elements

      As of jQuery 14 the change event bubbles in Internet Explorer behaving consistent ly with theevent in other modern browsers

      Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

      Javascript

      $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) change()

      CSS

      div colorred

      HTML

      ltselect name=sweets multiple=multiplegt ltoptiongtChocolateltoptiongt ltoption selected=selectedgtCandyltoptiongt

      ltoptiongtTaffyltoptiongt ltoption selected=selectedgtCaramelltoptiongt ltoptiongtFudgeltoptiongt ltoptiongtCookieltoptiongt

      ltselectgt ltdivgtltdivgt

      Example 2 To add a validity test to all text input elements

      Javascript

      $(input[type=text])change( function() check input ($(this)val()) for validity here)

      blur

      Bind an event handler to the blur JavaScript event or t rigger that event on an element

      Added in version 10

      blur()jQuery

      This method is a shortcut for bind(blur handler) in the f irst two variat ions and t rigger(blur) inthe third

      The blur event is sent to an element when it loses focus Originally this event was only

      applicable to form elements such as ltinputgt In recent browsers the domain of the event hasbeen extended to include all element types An element can lose focus via keyboardcommands such as the Tab key or by mouse clicks elsewhere on the page

      For example consider the HTML

      ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgtThe event handler can be bound to the first input field$(target)blur(function() alert(Handler for blur() called))

      Now if the f irst f ield has the focus clicking elsewhere or tabbing away from it displays the alert

      Handler for blur() called

      To trigger the event programmatically apply blur() without an argument

      $(other)cl ick(function() $(target)blur())

      After this code executes clicks on Trigger the handler will also alert the message

      The blur event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the blur event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping blur to the focusout event in its eventdelegat ion methods live() and delegate()

      Example 1 To trigger the blur event on all paragraphs

      Javascript

      $(p)blur()

      focus

      Bind an event handler to the focus JavaScript event or t rigger that event on an element

      Added in version 10

      focus()jQuery

      This method is a shortcut for bind(focus handler) in the f irst and second variat ionsand t rigger(focus) in the third

      The focus event is sent to an element when it gains focus This event is implicit lyapplicable to a limited set of elements such as form elements (ltinputgt ltselectgt etc) andlinks (lta hrefgt) In recent browser versions the event can be extended to include allelement types by explicit ly set t ing the element s tabindex property An element can gainfocus via keyboard commands such as the Tab key or by mouse clicks on the element

      Elements with focus are usually highlighted in some way by the browser for examplewith a dotted line surrounding the element The focus is used to determine which elementis the f irst to receive keyboard-related events

      For example consider the HTML

      ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the f irst input f ield

      $(target)focus(function() alert(Handler for focus() called))

      Now clicking on the f irst f ield or tabbing to it f rom another f ield displays the alert

      Handler for focus() called

      We can trigger the event when another element is clicked

      $(other)cl ick(function() $(target)focus())

      After this code executes clicks on Trigger the handler will also alert the message

      The focus event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the focus event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping focus to the focusin event in its event

      delegat ion methods live() and delegate()

      Triggering the focus on hidden elements causes an error in Internet ExplorerTake care to only call focus() without parameters on elements that are visible

      Example 1 Fire focus

      CSS

      span displaynone

      Javascript

      $(input)focus(function () $(this)next(span)css(display inl ine)fadeOut(1000) )

      HTML

      ltpgtltinput type=text gt ltspangtfocus fireltspangtltpgt

      ltpgtltinput type=password gt ltspangtfocus fireltspangtltpgt

      Example 2 To stop people f rom writ ing in text input boxes t ry

      Javascript

      $(input[type=text])focus(function() $(this)blur())

      Example 3 To focus on a login input box with id login on page startup t ry

      Javascript

      $(document)ready(function() $(login)focus())

      serializeArray

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

      Added in version 12

      serializeArray()Array

      The serializeArray() method creates a JavaScript array of objects ready to be encoded as aJSON string It operates on a jQuery object represent ing a set of form elements The formelements can be of several types

      ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

      The serializeArray() method uses the standard W3C rules for successful controls to determinewhich elements it should include in part icular the element cannot be disabled and must containa name attribute No submit button value is serialized since the form was not submit ted using abutton Data f rom f ile select elements is not serialized

      This method can act on a jQuery object that has selected individual form elements such asltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgt tag itselffor serializat ion

      $(form)submit(function() consolelog($(this)serial izeArray()) return false)

      This produces the following data structure (provided that the browser supports consolelog)

      [ name a value 1 name b value 2 name c value 3 name d value 4 name e value 5 ]

      Example 1 Get the values from a form iterate through them and append them to a resultsdisplay

      Javascript

      function showValues() var fields = $(input)serial izeArray() $(results)empty() jQueryeach(fields function(i field) $(results)append(fieldvalue + ) )

      $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

      CSS

      body select font-size14px form margin5px p colorred margin5px b colorblue

      HTML

      ltpgtltbgtResultsltbgt ltspan id=resultsgtltspangtltpgt

      ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

      ltselectgt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

      ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

      ltlabel for=ch1gtcheck1ltlabelgt ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

      ltlabel for=ch2gtcheck2ltlabelgt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

      ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

      ltlabel for=r2gtradio2ltlabelgt ltformgt

      serialize

      Encode a set of form elements as a string for submission

      Added in version 10

      serialize()String

      The serialize() method creates a text string in standard URL-encoded notat ion It operates ona jQuery object represent ing a set of form elements The form elements can be of severaltypes

      ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

      The serialize() method can act on a jQuery object that has selected individual form elementssuch as ltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgttag itself for serializat ion

      $(form)submit(function() alert($(this)serial ize()) return false)

      This produces a standard-looking query string

      a=1ampb=2ampc=3ampd=4ampe=5

      Warning select ing both the form and its children will cause duplicates in the serialized string

      Note Only successful controls are serialized to the string No submit button value is serializedsince the form was not submit ted using a button For a form element s value to be included inthe serialized string the element must have a name attribute Values from checkboxes andradio buttons (inputs of type radio or checkbox) are included only if they are checked Datafrom f ile select elements is not serialized

      Example 1 Serialize a form to a query string that could be sent to a server in an Ajax request

      Javascript

      function showValues() var str = $(form)serial ize() $(results)text(str) $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

      CSS

      body select font-size12px form margin5px p colorred margin5px font-size14px b colorblue

      HTML

      ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

      ltbr gt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

      ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

      ltlabel for=ch1gtcheck1ltlabelgt

      ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

      ltlabel for=ch2gtcheck2ltlabelgtltbr gt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

      ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

      ltlabel for=r2gtradio2ltlabelgt ltformgt ltpgtlttt id=resultsgtltttgtltpgt

      jQueryparam

      Create a serialized representat ion of an array or object suitable for use in a URL query string orAjax request

      Added in version 14

      jQueryparam(obj t radit ional)String

      objArray Object An array or object to serialize

      t radit ionalBoolean A Boolean indicat ing whether to perform a tradit ional shallowserializat ion

      This funct ion is used internally to convert form element values into a serialized stringrepresentat ion (See serialize() for more informat ion)

      As of jQuery 13 the return value of a funct ion is used instead of the funct ion as a String

      As of jQuery 14 the $param() method serializes deep objects recursively to accommodatemodern script ing languages and frameworks such as PHP and Ruby on Rails You can disablethis funct ionality globally by sett ing jQueryajaxSett ingst radit ional = t rue

      If the object passed is in an Array it must be an array of objects in the format returned byserializeArray()

      [namefirstvalueRicknamelastvalueAstleynamejobvalueRock Star]

      Note Because some frameworks have limited ability to parse serialized arraysdevelopers should exercise caution when passing an obj argument that containsobjects or arrays nested within another array

      Note Because there is no universally agreed-upon specification for param stringsit is not possible to encode complex data structures using this method in a mannerthat works ideally across all languages supporting such input Until such time thatthere is the $param method will remain in its current form

      In jQuery 14 HTML5 input elements are also serialized

      We can display a query string representat ion of an object and a URI-decoded version of the

      same as follows

      var myObject = a one 1 two 2 three 3 b [123]var recursiveEncoded = $param(myObject)var recursiveDecoded = decodeURIComponent($param(myObject))

      alert(recursiveEncoded)alert(recursiveDecoded)

      The values of recursiveEncoded and recursiveDecoded are alerted as follows

      a5Bone5D=1ampa5Btwo5D=2ampa5Bthree5D=3ampb5B5D=1ampb5B5D=2ampb5B5D=3

      a[one]=1ampa[two]=2ampa[three]=3ampb[]=1ampb[]=2ampb[]=3

      To emulate the behavior of $param() prior to jQuery 14 we can set the t radit ional argument totrue

      var myObject = a one 1 two 2 three 3 b [123]var shallowEncoded = $param(myObject true)var shallowDecoded = decodeURIComponent(shallowEncoded)

      alert(shallowEncoded)alert(shallowDecoded)

      The values of shallowEncoded and shallowDecoded are alerted as follows

      a=5Bobject+Object5Dampb=1ampb=2ampb=3

      a=[object+Object ]ampb=1ampb=2ampb=3

      Example 1 Serialize a keyvalue object

      Javascript

      var params = width1680 height1050 var str = jQueryparam(params) $(results)text(str)

      CSS

      div colorred

      HTML

      ltdiv id=resultsgtltdivgt

      Example 2 Serialize a few complex objects

      Javascript

      lt=132 $param( a [234] ) a=2ampa=3ampa=4 gt=14$param( a [234] ) a[]=2ampa[]=3ampa[]=4

      lt=132 $param( a b1c2 d [34 e5 ] ) a=[object+Object]ampd=3ampd=4ampd=[object+Object] gt=14 $param( a b1c2 d [34 e5 ] ) a[b]=1ampa[c]=2ampd[]=3ampd[]=4ampd[2][e]=5

      CSS

      div colorred

      val see Attributes

      val see Attributes

      Events

      toggle

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

      Added in version 10

      toggle(handler(eventObject) handler(eventObject) handler(eventObject))jQuery

      handler(eventObject)Funct ion A funct ion to execute every even t ime the element isclicked

      handler(eventObject)Funct ion A funct ion to execute every odd t ime the element isclicked

      handler(eventObject)Funct ion (opt ional) Addit ional handlers to cycle through af terclicks

      The toggle() method binds a handler for the click event so the rules out lined for the t riggeringof click apply here as well

      For example consider the HTMLltdiv id=targetgt Click hereltdivgt

      Event handlers can then bebound to the ltdivgt

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

      First handler for toggle() called

      Second handler for toggle() called

      First handler for toggle() called

      Second handler for toggle() called

      First handler for toggle() called

      If more than two handlers are provided toggle() will cycle among all of them For example ifthere are three handlers then the f irst handler will be called on the f irst click the fourth clickthe seventh click and so on

      Note jQuery also provides an animation method named toggle() that toggles the

      visibility of elements Whether the animation or the event method is fired dependson the set of arguments passed

      The toggle() method is provided for convenience It is relat ively straightforward to implementthe same behavior by hand and this can be necessary if the assumptions built into toggle()prove limit ing For example toggle() is not guaranteed to work correct ly if applied twice to thesame element Since toggle() internally uses a click handler to do its work we must unbind clickto remove a behavior at tached with toggle() so other click handlers can be caught in thecrossf ire The implementat ion also calls preventDefault () on the event so links will not befollowed and buttons will not be clicked if toggle() has been called on the element

      Example 1 Click to toggle highlight on the list item

      Javascript

      $(l i)toggle( function () $(this)css(list-style-typedisc colorblue) function () $(this)css(list-style-typedisc colorred) function () $(this)css(list-style-type color) )

      CSS

      ul margin10px l ist-styleinside circle font-weightbold l i cursorpointer

      HTML

      ltulgt ltligtGo to the storeltligt ltligtPick up dinnerltligt ltligtDebug crashltligt

      ltligtTake a jogltligt ltulgt

      Example 2 To toggle a style on table cells

      Javascript

      Javascript

      $(td)toggle( function () $(this)addClass(selected) function () $(this)removeClass(selected) )

      eventnamespace

      The namespace specif ied when the event was triggered

      Added in version 143

      This will likely be used primarily by plugin authors who wish to handle tasks dif ferent lydepending on the event namespace used

      Example 1 Determine the event namespace used

      Javascript

      $(p)bind(testsomething function(event) alert( eventnamespace ))$(button)cl ick(function(event) $(p)trigger(testsomething))

      HTML

      ltbuttongtdisplay eventnamespaceltbuttongtltpgtltpgt

      undelegate

      Remove a handler f rom the event for all elements which match the current selector now or inthe future based upon a specif ic set of root elements

      Added in version 16

      undelegate(namespace)jQuery

      namespaceString A string containing a namespace to unbind all events f rom

      Undelegate is a way of removing event handlers that have been bound using delegate() Itworks virtually ident ically to die() with the addit ion of a selector f ilter argument (which isrequired for delegat ion to work)

      Example 1 Can bind and unbind events to the colored button

      Javascript

      function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(body)delegate(theone cl ick aClick) find(theone)text(Can Click))$(unbind)cl ick(function () $(body)undelegate(theone cl ick aClick) find(theone)text(Does nothing))

      CSS

      button margin5px buttontheone colorred backgroundyellow

      HTML

      ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongtltdiv style=displaynonegtClickltdivgt

      Example 2 To unbind all delegated events f rom all paragraphs write

      Javascript

      $(p)undelegate()

      Example 3 To unbind all delegated click events f rom all paragraphs write

      Javascript

      $(p)undelegate( cl ick )

      Example 4 To undelegate just one previously bound handler pass the funct ion in as the third

      argument

      Javascript

      var foo = function () code to handle some kind of event

      now foo wil l be called when paragraphs are cl icked $(body)delegate(p cl ick foo)

      foo wil l no longer be called$(body)undelegate(p cl ick foo)

      Example 5 To unbind all delegated events by their namespace

      Javascript

      var foo = function () code to handle some kind of event

      delegate events under the whatever namespace$(form)delegate(button cl ickwhatever foo)

      $(form)delegate(input[type=text] keypresswhatever foo)

      unbind all events delegated under the whatever namespace

      $(form)undelegate(whatever)

      delegate

      Attach a handler to one or more events for all elements that match the selector now or in thefuture based on a specif ic set of root elements

      Added in version 143

      delegate(selector events)jQuery

      selectorString A selector to f ilter the elements that t rigger the event

      eventsMap A map of one or more event types and funct ions to execute for them

      Delegate is an alternat ive to using the live() method allowing for each binding of eventdelegat ion to specif ic DOM elements For example the following delegate code

      $(table)delegate(td hover function() $(this)toggleClass(hover))

      Is equivalent to the following code writ ten using live()

      $(table)each(function() $(td this)l ive(hover function() $(this)toggleClass(hover) ))

      See also the undelegate() method for a way of removing event handlers added in delegate()

      Passing and handling event data works the same way as it does for bind()

      Example 1 Click a paragraph to add another Note that delegate() binds the click event to allparagraphs - even new ones

      Javascript

      $(body)delegate(p cl ick function() $(this)after(ltpgtAnother paragraphltpgt) )

      CSS

      p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

      HTML

      ltpgtClick meltpgt

      ltspangtltspangt

      Example 2 To display each paragraphs text in an alert box whenever it is clicked

      Javascript

      $(body)delegate(p cl ick function() alert( $(this)text() ))

      Example 3 To cancel a default act ion and prevent it f rom bubbling up return false

      Javascript

      $(body)delegate(a cl ick function() return false )

      Example 4 To cancel only the default act ion by using the preventDefault method

      Javascript

      $(body)delegate(a cl ick function(event) eventpreventDefault())

      Example 5 Can bind custom events too

      Javascript

      $(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)cl ick(function () $(p)trigger(myCustomEvent) )

      CSS

      p colorred span colorblue

      HTML

      ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

      jQueryproxy

      Takes a funct ion and returns a new one that will always have a part icular context

      Added in version 14

      jQueryproxy(context name)Funct ion

      context Object The object to which the context of the funct ion should be set

      nameString The name of the funct ion whose context will be changed (should be aproperty of the context object)

      This method is most useful for at taching event handlers to an element where the context ispoint ing back to a dif ferent object Addit ionally jQuery makes sure that even if you bind thefunct ion returned from jQueryproxy() it will st ill unbind the correct funct ion if passed theoriginal

      Example 1 Change the context of funct ions bound to a click handler using the funct ioncontext signature Unbind the f irst handler af ter f irst click

      HTML

      ltpgtltbutton type=button id=testgtTestltbuttongtltpgtltdiv id=loggtltdivgt

      Javascript

      var me = type zombie test function(event) Without proxy `this` would refer to the event target use eventtarget to reference that element var element = eventtarget $(element)css(background-color red)

      With proxy `this` refers to the me object encapsulating this function $(log)append( Hello + thistype + ltbrgt ) $(test)unbind(click thistest)

      var you = type person test function(event) $(log)append( thistype + )

      execute youtest() in the context of the `you` object no matter where it is called i e the `this` keyword wil l refer to `you`var youClick = $proxy( youtest you )

      attach click handlers to test$(test) this === zombie handler unbound after first cl ick cl ick( $proxy( metest me ) ) this === person cl ick( youClick ) this === zombie cl ick( $proxy( youtest me ) ) this === ltbuttongt element cl ick( youtest )

      Example 2 Enforce the context of the funct ion using the context funct ion name signatureUnbind the handler af ter f irst click

      HTML

      ltpgtltbutton id=testgtTestltbuttongtltpgt ltp id=loggtltpgt

      Javascript

      var obj = name John test function() $(log)append( thisname ) $(test)unbind(click objtest)

      $(test)cl ick( jQueryproxy( obj test ) )

      focusout

      Bind an event handler to the focusout JavaScript event

      Added in version 143

      focusout(eventData handler(eventObject))jQuery

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

      This method is a shortcut for bind(focusout handler)

      The focusout event is sent to an element when it or any element inside of it loses focus Thisis dist inct f rom the blur event in that it supports detect ing the loss of focus from parentelements (in other words it supports event bubbling)

      This event will likely be used together with the focusin event

      Example 1 Watch for a loss of focus to occur inside paragraphs and note the dif ferencebetween the focusout count and the blur count

      CSS

      inputs float left margin-right 1em

      inputs p margin-top 0

      Javascript

      var fo = 0 b = 0$(p)focusout(function() fo++ $(fo) text(focusout fired + fo + x))blur(function() b++ $(b) text(blur fired + b + x) )

      HTML

      ltdiv class=inputsgt ltpgt ltinput type=text gtltbr gt ltinput type=text gt ltpgt ltpgt ltinput type=password gt ltpgtltdivgtltdiv id=fogtfocusout fireltdivgtltdiv id=bgtblur fireltdivgt

      focusin

      Bind an event handler to the focusin JavaScript event

      Added in version 143

      focusin(eventData handler(eventObject))jQuery

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

      This method is a shortcut for bind(focusin handler)

      The focusin event is sent to an element when it or any element inside of it gains focus This isdist inct f rom the focus event in that it supports detect ing the focus event on parent elements(in other words it supports event bubbling)

      This event will likely be used together with the focusout event

      Example 1 Watch for a focus to occur within the paragraphs on the page

      CSS

      span displaynone

      Javascript

      $(p)focusin(function() $(this)find(span)css(display inl ine)fadeOut(1000) )

      HTML

      ltpgtltinput type=text gt ltspangtfocusin fireltspangtltpgtltpgtltinput type=password gt ltspangtfocusin fireltspangtltpgt

      eventisImmediatePropagationStopped

      Returns whether eventstopImmediatePropagat ion() was ever called on this event object

      Added in version 13

      eventisImmediatePropagat ionStopped()Boolean

      This property was introduced in DOM level 3

      Example 1 Checks whether eventstopImmediatePropagat ion() was called

      Javascript

      function immediatePropStopped(e) var msg = i f ( eisImmediatePropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

      $(button)cl ick(function(event) immediatePropStopped(event) eventstopImmediatePropagation() immediatePropStopped(event))

      HTML

      ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

      eventstopImmediatePropagation

      Keeps the rest of the handlers f rom being executed and prevents the event f rom bubbling upthe DOM tree

      Added in version 13

      eventstopImmediatePropagat ion()

      In addit ion to keeping any addit ional handlers on an element f rom being executed this methodalso stops the bubbling by implicit ly calling eventstopPropagat ion() To simply prevent theevent f rom bubbling to ancestor elements but allow other event handlers to execute on thesame element we can use eventstopPropagat ion() instead

      Use eventisImmediatePropagat ionStopped() to know whether this method was ever called (onthat event object)

      Example 1 Prevents other event handlers f rom being called

      CSS

      p height 30px width 150px background-color ccf div height 30px width 150px background-color cfc

      Javascript

      $(p)cl ick(function(event) eventstopImmediatePropagation())$(p)cl ick(function(event) This function wont be executed $(this)css(background-color f00)) $(div)cl ick(function(event) This function wil l be executed $(this)css(background-color f00))

      HTML

      ltpgtparagraphltpgtltdivgtdivisionltdivgt

      eventisPropagationStopped

      Returns whether eventstopPropagat ion() was ever called on this event object

      Added in version 13

      eventisPropagat ionStopped()Boolean

      This event method is described in the W3C DOM Level 3 specif icat ion

      Example 1 Checks whether eventstopPropagat ion() was called

      Javascript

      function propStopped(e) var msg = i f ( eisPropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

      $(button)cl ick(function(event) propStopped(event) eventstopPropagation() propStopped(event))

      HTML

      ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

      eventstopPropagation

      Prevents the event f rom bubbling up the DOM tree prevent ing any parent handlers f rom beingnot if ied of the event

      Added in version 10

      eventstopPropagat ion()

      We can use eventisPropagat ionStopped() to determine if this method was ever called (on thatevent object)

      This method works for custom events t riggered with t rigger() as well

      Note that this will not prevent other handlers on the same element f rom running

      Example 1 Kill the bubbling on the click event

      Javascript

      $(p)cl ick(function(event) eventstopPropagation() do something)

      eventisDefaultPrevented

      Returns whether eventpreventDefault () was ever called on this event object

      Added in version 13

      eventisDefaultPrevented()Boolean

      Example 1 Checks whether eventpreventDefault () was called

      Javascript

      $(a)cl ick(function(event) alert( eventisDefaultPrevented() ) false eventpreventDefault() alert( eventisDefaultPrevented() ) true)

      eventpreventDefault

      If this method is called the default act ion of the event will not be triggered

      Added in version 10

      eventpreventDefault ()undef ined

      For example clicked anchors will not take the browser to a new URL We can useeventisDefaultPrevented() to determine if this method has been called by an event handlerthat was triggered by this event

      Example 1 Cancel the default act ion (navigat ion) of the click

      Javascript

      $(a)cl ick(function(event) eventpreventDefault() $(ltdivgt) append(default + eventtype + prevented) appendTo(log))

      HTML

      lta href=httpjquerycomgtdefault cl ick action is preventedltagtltdiv id=loggtltdivgt

      eventtimeStamp

      The dif ference in milliseconds between the t ime an event is t riggered and January 1 1970

      Added in version 126

      This property can be useful for prof iling the performance of certain jQuery funct ions by gett ingthe eventt imeStamp value at two points in the code and not ing the dif ference

      Example 1 Display the t ime since the click handler last executed

      CSS

      div height 100px width 300px margin 10px background-color ffd overflow auto

      Javascript

      var last diff$(div)cl ick(function(event) if ( last ) diff = eventtimeStamp - last $(div)append(time since last event + diff + ltbrgt) else $(div)append(Click againltbrgt) last = eventtimeStamp)

      HTML

      ltdivgtClickltdivgt

      eventresult

      The last value returned by an event handler that was triggered by this event unless the valuewas undef ined

      Added in version 13

      This property can be useful for gett ing previous return values of custom events

      Example 1 Display previous handlers return value

      Javascript

      $(button)cl ick(function(event) return hey)$(button)cl ick(function(event) $(p)html( eventresult ))

      HTML

      ltbuttongtdisplay eventresultltbuttongtltpgtltpgt

      eventwhich

      For key or button events this at t ribute indicates the specif ic button or key that was pressed

      Added in version 113

      eventwhich normalizes eventkeyCode and eventcharCode It is recommended to watcheventwhich for keyboard key input For more detail read about eventcharCode on the MDC

      Example 1 Log what key was depressed

      Javascript

      $(whichkey)bind(keydownfunction(e) $(log)html(etype + + ewhich ))

      HTML

      ltinput id=whichkey value=type somethinggtltdiv id=loggtltdivgt

      Results

      keydown 74

      eventpageY

      The mouse posit ion relat ive to the top edge of the document

      Added in version 104

      Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthis if rame)

      CSS

      body background-color eef div padding 20px

      HTML

      ltdiv id=loggtltdivgt

      Javascript

      $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

      eventpageX

      The mouse posit ion relat ive to the lef t edge of the document

      Added in version 104

      Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthe if rame)

      CSS

      body background-color eef div padding 20px

      HTML

      ltdiv id=loggtltdivgt

      Javascript

      $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

      eventcurrentTarget

      The current DOM element within the event bubbling phase

      Added in version 13

      This property will typically be equal to the this of the funct ion

      If you are using jQueryproxy or another form of scope manipulation this will be equal towhatever context you have provided not eventcurrentTarget

      Example 1 Alert that currentTarget matches the `this` keyword

      Javascript

      $(p)cl ick(function(event) alert( eventcurrentTarget === this ) true)

      eventrelatedTarget

      The other DOM element involved in the event if any

      Added in version 114

      For mouseout indicates the element being entered for mouseover indicates the elementbeing exited

      Example 1 On mouseout of anchors alert the element type being entered

      Javascript

      $(a)mouseout(function(event) alert(eventrelatedTargetnodeName) DIV)

      eventdata

      The opt ional data passed to jQueryfnbind when the current execut ing handler was bound

      Added in version 11

      Example 1 The descript ion of the example

      Javascript

      $(a)each(function(i) $(this)bind(cl ick indexi function(e) alert(my index is + edataindex) ))

      eventtarget

      The DOM element that init iated the event

      Added in version 10

      The target property can be the element that registered for the event or a descendant of it It isof ten useful to compare eventtarget to this in order to determine if the event is being handleddue to event bubbling This property is very useful in event delegat ion when events bubble

      Example 1 Display the tags name on click

      Javascript

      $(body)cl ick(function(event) $(log)html(clicked + eventtargetnodeName))

      CSS

      span strong p padding 8px display block border 1px solid 999

      HTML

      ltdiv id=loggtltdivgtltdivgt ltpgt ltstronggtltspangtclickltspangtltstronggt ltpgtltdivgt

      Example 2 Implements a simple event delegat ion The click handler is added to an unorderedlist and the children of its li children are hidden Clicking one of the li children toggles (seetoggle()) their children

      Javascript

      function handler(event) var $target = $(eventtarget) i f( $targetis( l i) ) $targetchildren()toggle() $(ul)cl ick(handler)find(ul)hide()

      HTML

      ltulgt ltligtitem 1 ltulgt ltligtsub item 1-altligt ltligtsub item 1-bltligt ltulgt ltl igt ltligtitem 2 ltulgt ltligtsub item 2-altligt ltligtsub item 2-bltligt ltulgt ltl igt ltulgt

      eventtype

      Describes the nature of the event

      Added in version 10

      Example 1 On all anchor clicks alert the event type

      Javascript

      $(a)cl ick(function(event) alert(eventtype) cl ick)

      keydown

      Bind an event handler to the keydown JavaScript event or t rigger that event on an element

      Added in version 10

      keydown()jQuery

      This method is a shortcut for bind(keydown handler) in the f irst and second variat ions and

      t rigger(keydown) in the third

      The keydown event is sent to an element when the user f irst presses a key on the keyboard Itcan be at tached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

      For example consider the HTML

      ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the input f ield

      $(target)keydown(function() alert(Handler for keydown() called))

      Now when the insert ion point is inside the f ield pressing a key displays the alert

      Handler for keydown() called

      To trigger the event manually apply keydown() without an argument

      $(other)cl ick(function() $(target)keydown())

      After this code executes clicks on Trigger the handler will also alert the message

      If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

      To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

      Example 1 Show the event object for the keydown handler when a key is pressed in the input

      Javascript

      var xTriggered = 0$(target)keydown(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keydown() called + xTriggered + time(s) $print(msg html) $print(event))

      $(other)cl ick(function() $(target)keydown())

      CSS

      fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

      HTML

      ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

      scroll

      Bind an event handler to the scroll JavaScript event or t rigger that event on an element

      Added in version 10

      scroll()jQuery

      This method is a shortcut for bind(scroll handler) in the f irst and second variat ions andtrigger(scroll) in the third

      The scroll event is sent to an element when the user scrolls to a dif ferent place in the elementIt applies to window objects but also to scrollable f rames and elements with the overf low CSSproperty set to scroll (or auto when the element s explicit height or width is less than the heightor width of its contents)

      For example consider the HTML

      ltdiv id=target style=overflow scroll width 200px height 100pxgt 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 al iquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt moll it anim id est laborumltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The style def init ion is present to make the target element small enough to be scrollable

      The scroll event handler can bebound to this element

      $(target)scroll(function() $(log)append(ltdivgtHandler for scroll() calledltdivgt))

      Now when the user scrolls the text up or down one or more messages are appended to ltdiv

      id=loggtltdivgt

      Handler for scroll() called

      To trigger the event manually apply scroll() without an argument

      $(other)cl ick(function() $(target)scroll())

      After this code executes clicks on Trigger the handler will also append the message

      A scroll event is sent whenever the element s scroll posit ion changes regardless of the causeA mouse click or drag on the scroll bar dragging inside the element pressing the arrow keys orusing the mouses scroll wheel could cause this event

      Example 1 To do something when your page is scrolled

      Javascript

      $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(window)scroll(function () $(span)css(display inl ine)fadeOut(slow) )

      CSS

      div colorblue p colorgreen span colorred displaynone

      HTML

      ltdivgtTry scroll ing the iframeltdivgt ltpgtParagraph - ltspangtScroll happenedltspangtltpgt

      resize

      Bind an event handler to the resize JavaScript event or t rigger that event on an element

      Added in version 10

      resize()jQuery

      This method is a shortcut for bind(resize handler) in the f irst and second variat ions andtrigger(resize) in the third

      The resize event is sent to the window element when the size of the browser window changes

      $(window)resize(function() $(log)append(ltdivgtHandler for resize() calledltdivgt))

      Now whenever the browser windows size is changed the message is appended to ltdivid=loggt one or more t imes depending on the browser

      Code in a resize handler should never rely on the number of t imes the handler is calledDepending on implementat ion resize events can be sent cont inuously as the resizing is inprogress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safariand Chrome) or only once at the end of the resize operat ion (the typical behavior in someother browsers such as Opera)

      Example 1 To see the window width while (or af ter) it is resized t ry

      Javascript

      $(window)resize(function() $(body)prepend(ltdivgt + $(window)width() + ltdivgt))

      keyup

      Bind an event handler to the keyup JavaScript event or t rigger that event on an element

      Added in version 10

      keyup()jQuery

      This method is a shortcut for bind(keyup handler) in the f irst two variat ions andtrigger(keyup) in the third

      The keyup event is sent to an element when the user releases a key on the keyboard It can beattached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

      For example consider the HTML

      ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the input f ield

      $(target)keyup(function() alert(Handler for keyup() called))

      Now when the insert ion point is inside the f ield and a key is pressed and released the alert isdisplayed

      Handler for keyup() called

      To trigger the event manually apply keyup() without arguments

      $(other)cl ick(function() $(target)keyup())

      After this code executes clicks on Trigger the handler will also alert the message

      If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

      To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

      Example 1 Show the event object for the keyup handler when a key is released in the input

      Javascript

      var xTriggered = 0$(target)keyup(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keyup() called + xTriggered + time(s) $print(msg html) $print(event))

      $(other)cl ick(function() $(target)keyup())

      CSS

      fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

      HTML

      ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

      keypress

      Bind an event handler to the keypress JavaScript event or t rigger that event on an element

      Added in version 10

      keypress()jQuery

      Note as the keypress event isnt covered by any of f icial specif icat ion the actual behaviorencountered when using it may dif fer across browsers browser versions and plat forms

      This method is a shortcut for bind(keypress handler) in the f irst two variat ions andtrigger(keypress) in the third

      The keypress event is sent to an element when the browser registers keyboard input This issimilar to the keydown event except in the case of key repeats If the user presses and holds akey a keydown event is t riggered once but separate keypress events are t riggered for eachinserted character In addit ion modif ier keys (such as Shif t ) t rigger keydown events but notkeypress events

      A keypress event handler can be at tached to any element but the event is only sent to theelement that has the focus Focusable elements can vary between browsers but formelements can always get focus so are reasonable candidates for this event type

      For example consider the HTML

      ltformgt ltfieldsetgt ltinput id=target type=text value=Hello there gt ltfieldsetgtltformgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be bound to the input f ield

      $(target)keypress(function() alert(Handler for keypress() called))

      Now when the insert ion point is inside the f ield pressing a key displays the alert

      Handler for keypress() called

      The message repeats if the key is held down To trigger the event manually apply keypress()without an argument

      $(other)cl ick(function() $(target)keypress())

      After this code executes clicks on Trigger the handler will also alert the message

      If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

      To determine which character was entered examine the event object that is passed to thehandler funct ion While browsers use dif fering propert ies to store this informat ion jQuerynormalizes the which property so you can reliably use it to retrieve the character code

      Note that keydown and keyup provide a code indicat ing which key is pressed while keypressindicates which character was entered For example a lowercase a will be reported as 65 bykeydown and keyup but as 97 by keypress An uppercase A is reported as 65 by all eventsBecause of this dist inct ion when catching special keystrokes such as arrow keys keydown() orkeyup() is a better choice

      Example 1 Show the event object when a key is pressed in the input Note This demo relies ona simple $print() plugin (ht tpapijquerycomscriptseventsjs) for the event object s output

      Javascript

      var xTriggered = 0$(target)keypress(function(event) if ( eventwhich == 13 ) eventpreventDefault() xTriggered++ var msg = Handler for keypress() called + xTriggered + time(s) $print( msg html ) $print( event ))

      $(other)cl ick(function() $(target)keypress())

      CSS

      fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

      HTML

      ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript src=httpapijquerycomscriptseventsjsgtltscriptgt

      submit see Forms

      select see Forms

      change see Forms

      blur see Forms

      focus see Forms

      mousemove

      Bind an event handler to the mousemove JavaScript event or t rigger that event on anelement

      Added in version 10

      mousemove()jQuery

      This method is a shortcut for bind(mousemove handler) in the f irst two variat ions andtrigger(mousemove) in the third

      The mousemove event is sent to an element when the mouse pointer moves inside theelement Any HTML element can receive this event

      For example consider the HTML

      ltdiv id=targetgt Move hereltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The event handler can be bound to the target

      $(target)mousemove(function(event) var msg = Handler for mousemove() called at msg += eventpageX + + eventpageY $(log)append(ltdivgt + msg + ltdivgt))

      Now when the mouse pointer moves within the target button the messages are appended toltdiv id=loggt

      Handler for mousemove() called at (399 48)

      Handler for mousemove() called at (398 46)

      Handler for mousemove() called at (397 44)

      Handler for mousemove() called at (396 42)

      To trigger the event manually apply mousemove() without an argument

      $(other)cl ick(function() $(target)mousemove())

      After this code executes clicks on the Trigger button will also append the message

      Handler for mousemove() called at (undef ined undef ined)

      When tracking mouse movement you usually need to know the actual posit ion of the mousepointer The event object that is passed to the handler contains some informat ion about themouse coordinates Propert ies such as clientX of fsetX and pageX are available but supportfor them dif fers between browsers Fortunately jQuery normalizes the pageX and pageYpropert ies so that they can be used in all browsers These propert ies provide the X and Ycoordinates of the mouse pointer relat ive to the top-lef t corner of the document as illustratedin the example output above

      Keep in mind that the mousemove event is t riggered whenever the mouse pointer moves evenfor a pixel This means that hundreds of events can be generated over a very small amount oft ime If the handler has to do any signif icant processing or if mult iple handlers for the eventexist this can be a serious performance drain on the browser It is important therefore toopt imize mousemove handlers as much as possible and to unbind them as soon as they areno longer needed

      A common pattern is to bind the mousemove handler f rom within a mousedown hander and tounbind it f rom a corresponding mouseup handler If implement ing this sequence of eventsremember that the mouseup event might be sent to a dif ferent HTML element than themousemove event was To account for this the mouseup handler should typically be bound toan element high up in the DOM tree such as ltbodygt

      Example 1 Show the mouse coordinates when the mouse is moved over the yellow divCoordinates are relat ive to the window which in this case is the if rame

      Javascript

      $(div)mousemove(function(e) var pageCoords = ( + epageX + + epageY + ) var cl ientCoords = ( + ecl ientX + + ecl ientY + ) $(spanfirst)text(( epageX epageY ) - + pageCoords) $(spanlast)text(( ecl ientX ecl ientY ) - + clientCoords) )

      CSS

      div width220px height170px margin10px margin-right50px backgroundyellow border2px groove floatright p margin0 margin-left10px colorred width220px height120px padding-top70px floatleft font-size14px span displayblock

      HTML

      ltpgt Try scroll ing too ltspangtMove the mouse over the divltspangt ltspangtampnbspltspangt ltpgt

      ltdivgtltdivgt

      hover

      Bind two handlers to the matched elements to be executed when the mouse pointer entersand leaves the elements

      Added in version 10

      hover(handlerIn(eventObject) handlerOut(eventObject))jQuery

      handlerIn(eventObject)Funct ion A funct ion to execute when the mouse pointerenters the element

      handlerOut(eventObject)Funct ion A funct ion to execute when the mouse pointerleaves the element

      The hover() method binds handlers for both mouseenter and mouseleave events You can useit to simply apply behavior to an element during the t ime the mouse is within the element

      Calling $(selector)hover(handlerIn handlerOut) is shorthand for

      $(selector)mouseenter(handlerIn)mouseleave(handlerOut)

      See the discussions for mouseenter() and mouseleave() for more details

      Example 1 To add a special style to list items that are being hovered over t ry

      Javascript

      $(l i)hover( function () $(this)append($(ltspangt ltspangt)) function () $(this)find(spanlast)remove() )

      l i with fade class$(l i fade)hover(function()$(this)fadeOut(100)$(this)fadeIn(500))

      CSS

      ul margin-left20px colorblue l i cursordefault span colorred

      HTML

      ltulgt ltligtMilkltligt ltligtBreadltligt ltli class=fadegtChipsltligt

      ltli class=fadegtSocksltligt ltulgt

      Example 2 To add a special style to table cells that are being hovered over t ry

      Javascript

      $(td)hover( function () $(this)addClass(hover) function () $(this)removeClass(hover) )

      Example 3 To unbind the above example use

      Javascript

      $(td)unbind(mouseenter mouseleave)

      hover

      Bind a single handler to the matched elements to be executed when the mouse pointer entersor leaves the elements

      Added in version 14

      hover(handlerInOut(eventObject))jQuery

      handlerInOut(eventObject)Funct ion A funct ion to execute when the mouse pointerenters or leaves the element

      The hover() method when passed a single funct ion will execute that handler for bothmouseenter and mouseleave events This allows the user to use jQuerys various togglemethods within the handler or to respond dif ferent ly within the handler depending on theeventtype

      Calling $(selector)hover(handlerInOut) is shorthand for

      $(selector)bind(mouseenter mouseleave handlerInOut)

      See the discussions for mouseenter() and mouseleave() for more details

      Example 1 Slide the next sibling LI up or down on hover and toggle a class

      Javascript

      $(l i)fi lter(odd)hide() end()fi lter(even)hover( function () $(this)toggleClass(active) next()stop(true true)sl ideToggle() )

      CSS

      ul margin-left20px colorblue l i cursordefault l i active backgroundblackcolorwhite span colorred

      HTML

      ltulgt ltligtMilkltligt ltligtWhiteltligt ltligtCarrotsltligt ltligtOrangeltligt ltligtBroccoliltl igt ltligtGreenltligt ltulgt

      mouseleave

      Bind an event handler to be f ired when the mouse leaves an element or t rigger that handler onan element

      Added in version 10

      mouseleave()jQuery

      This method is a shortcut for bind(mouseleave handler) in the f irst two variat ions andtrigger(mouseleave) in the third

      The mouseleave JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer leaves the element Any HTML elementcan receive this event

      For example consider the HTML

      ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The event handler can be boundto any element

      $(outer)mouseleave(function() $(log)append(ltdivgtHandler for mouseleave() calledltdivgt))

      Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

      $(other)cl ick(function() $(outer)mouseleave())

      After this code executes clicks on Trigger the handler will also append the message

      The mouseleave event dif fers f rom mouseout in the way it handles event bubbling If mouseoutwere used in this example then when the mouse pointer moved out of the Inner element thehandler would be triggered This is usually undesirable behavior The mouseleave event on theother hand only t riggers its handler when the mouse leaves the element it is bound to not adescendant So in this example the handler is t riggered when the mouse leaves the Outerelement but not the Inner element

      Example 1 Show number of t imes mouseout and mouseleave events are t riggered mouseoutf ires when the pointer moves out of child element as well while mouseleave f ires only when thepointer moves out of the bound element

      CSS

      divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

      Javascript

      var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) )mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )

      var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) )mouseleave(function() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

      HTML

      ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      mouseenter

      Bind an event handler to be f ired when the mouse enters an element or t rigger that handler onan element

      Added in version 10

      mouseenter()jQuery

      This method is a shortcut for bind(mouseenter handler) in the f irst two variat ions andtrigger(mouseenter) in the third

      The mouseenter JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer enters the element Any HTML elementcan receive this event

      For example consider the HTML

      ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The event handler can be boundto any element

      $(outer)mouseenter(function() $(log)append(ltdivgtHandler for mouseenter() calledltdivgt))

      Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

      $(other)cl ick(function() $(outer)mouseenter())

      After this code executes clicks on Trigger the handler will also append the message

      The mouseenter event dif fers f rom mouseover in the way it handles event bubbling Ifmouseover were used in this example then when the mouse pointer moved over the Innerelement the handler would be triggered This is usually undesirable behavior The mouseenterevent on the other hand only t riggers its handler when the mouse enters the element it isbound to not a descendant So in this example the handler is t riggered when the mouse entersthe Outer element but not the Inner element

      Example 1 Show texts when mouseenter and mouseout event t riggering mouseover f ireswhen the pointer moves into the child element as well while mouseenter f ires only when thepointer moves into the bound element

      CSS

      divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

      Javascript

      var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) $(plastthis)text(++i) )mouseout(function() $(pfirstthis)text(mouse out) )

      var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) $(plastthis)text(++n) )mouseleave(function() $(pfirstthis)text(mouse leave) )

      HTML

      ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      mouseout

      Bind an event handler to the mouseout JavaScript event or t rigger that event on an element

      Added in version 10

      mouseout()jQuery

      This method is a shortcut for bind(mouseout handler) in the f irst two variat ion andtrigger(mouseout ) in the third

      The mouseout event is sent to an element when the mouse pointer leaves the element AnyHTML element can receive this event

      For example consider the HTML

      ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The event handler can be boundto any element

      $(outer)mouseout(function() $(log)append(Handler for mouseout() called))

      Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt To trigger the event manually apply mouseout() without an argument

      $(other)cl ick(function() $(outer)mouseout())

      After this code executes clicks on Trigger the handler will also append the message

      This event type can cause many headaches due to event bubbling For instance when themouse pointer moves out of the Inner element in this example a mouseout event will be sentto that then trickle up to Outer This can trigger the bound mouseout handler at inopportunet imes See the discussion for mouseleave() for a useful alternat ive

      Example 1 Show the number of t imes mouseout and mouseleave events are t riggeredmouseout f ires when the pointer moves out of the child element as well while mouseleave f iresonly when the pointer moves out of the bound element

      CSS

      divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

      Javascript

      var i = 0 $(divoverout)mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )mouseover(function() $(pfirstthis)text(mouse over) )

      var n = 0 $(diventerleave)bind(mouseenterfunction() $(pfirstthis)text(mouse enter) )bind(mouseleavefunction() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

      HTML

      ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

      mouseover

      Bind an event handler to the mouseover JavaScript event or t rigger that event on anelement

      Added in version 10

      mouseover()jQuery

      This method is a shortcut for bind(mouseover handler) in the f irst two variat ions andtrigger(mouseover) in the third

      The mouseover event is sent to an element when the mouse pointer enters the element AnyHTML element can receive this event

      For example consider the HTML

      ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

      The event handler can be boundto any element

      $(outer)mouseover(function() $(log)append(ltdivgtHandler for mouseover() calledltdivgt))

      Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt We can also t rigger the event when another element is clicked

      $(other)cl ick(function() $(outer)mouseover())

      After this code executes clicks on Trigger the handler will also append the message

      This event type can cause many headaches due to event bubbling For instance when themouse pointer moves over the Inner element in this example a mouseover event will be sent tothat then trickle up to Outer This can trigger our bound mouseover handler at inopportunet imes See the discussion for mouseenter() for a useful alternat ive

      Example 1 Show the number of t imes mouseover and mouseenter events are t riggeredmouseover f ires when the pointer moves into the child element as well while mouseenter f iresonly when the pointer moves into the bound element

      CSS

      divout width40 height120px margin0 15px background-colorD6EDFC floatleft divin width60 height60 background-colorFFCC00 margin10px auto p l ine-height1em margin0 padding0

      Javascript

      var i = 0 $(divoverout)mouseover(function() i += 1 $(this)find(span)text( mouse over x + i ) )mouseout(function() $(this)find(span)text(mouse out ) )

      var n = 0 $(diventerleave)mouseenter(function() n += 1 $(this)find(span)text( mouse enter x + n ) )mouseleave(function() $(this)find(span)text(mouse leave) )

      HTML

      ltdiv class=out overoutgt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

      ltdiv class=out enterleavegt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

      dblclick

      Bind an event handler to the dblclick JavaScript event or t rigger that event on an element

      Added in version 10

      dblclick()jQuery

      This method is a shortcut for bind(dblclick handler) in the f irst two variat ions andtrigger(dblclick) in the third The dblclick event is sent to an element when the element isdouble-clicked Any HTML element can receive this event For example consider the HTML

      ltdiv id=targetgt Double-click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be boundto any ltdivgt

      $(target)dblcl ick(function() alert(Handler for dblcl ick() called))

      Now double-clicking on this element displays the alert

      Handler for dblclick() called

      To trigger the event manually apply dblclick() without an argument

      $(other)cl ick(function() $(target)dblcl ick())

      After this code executes (single) clicks on Trigger the handler will also alert the message

      The dblclick event is only t riggered af ter this exact series of events

      The mouse button is depressed while the pointer is inside the element

      The mouse button is released while the pointer is inside the element

      The mouse button is depressed again while the pointer is inside the element within at ime window that is system-dependent

      The mouse button is released while the pointer is inside the element

      It is inadvisable to bind handlers to both the click and dblclick events for the same element Thesequence of events t riggered varies f rom browser to browser with some receiving two clickevents before the dblclick and others only one Double-click sensit ivity (maximum t ime betweenclicks that is detected as a double click) can vary by operat ing system and browser and is of tenuser-conf igurable

      Example 1 To bind a Hello World alert box the dblclick event on every paragraph on the page

      Javascript

      $(p)dblcl ick( function () alert(Hello World) )

      Example 2 Double click to toggle background color

      Javascript

      var divdbl = $(divfirst) divdbldblcl ick(function () divdbltoggleClass(dbl) )

      CSS

      div backgroundblue colorwhite height100px width150px divdbl backgroundyellowcolorblack

      HTML

      ltdivgtltdivgtltspangtDouble cl ick the blockltspangt

      click

      Bind an event handler to the click JavaScript event or t rigger that event on an element

      Added in version 10

      click()jQuery

      This method is a shortcut for bind(click handler) in the f irst two variat ions and t rigger(click)in the third

      The click event is sent to an element when the mouse pointer is over the element and themouse button is pressed and released Any HTML element can receive this event

      For example consider the HTMLltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be boundto any ltdivgt

      $(target)cl ick(function() alert(Handler for cl ick() called))

      Now if we click on this element the alert is displayed

      Handler for click() called

      We can also t rigger the event when a dif ferent element is clicked

      $(other)cl ick(function() $(target)cl ick())

      After this code executes clicks on Trigger the handler will also alert the message

      The click event is only t riggered af ter this exact series of events

      The mouse button is depressed while the pointer is inside the element

      The mouse button is released while the pointer is inside the element

      This is usually the desired sequence before taking an act ion If this is not required themousedown or mouseup event may be more suitable

      Example 1 To hide paragraphs on a page when they are clicked

      Javascript

      $(p)cl ick(function () $(this)sl ideUp() ) $(p)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

      CSS

      p colorred margin5px cursorpointer phil ite backgroundyellow

      HTML

      ltpgtFirst Paragraphltpgt

      ltpgtSecond Paragraphltpgt ltpgtYet one more Paragraphltpgt

      Example 2 To trigger the click event on all of the paragraphs on the page

      Javascript

      $(p)cl ick()

      mouseup

      Bind an event handler to the mouseup JavaScript event or t rigger that event on an element

      Added in version 10

      mouseup()jQuery

      This method is a shortcut for bind(mouseup handler) in the f irst variat ion andtrigger(mouseup) in the second

      The mouseup event is sent to an element when the mouse pointer is over the element and themouse button is released Any HTML element can receive this event

      For example consider the HTML

      ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be boundto any ltdivgt

      $(target)mouseup(function() alert(Handler for mouseup() called))

      Now if we click on this element the alert is displayed

      Handler for mouseup() called

      We can also t rigger the event when a dif ferent element is clicked

      $(other)cl ick(function() $(target)mouseup())

      After this code executes clicks on Trigger the handler will also alert the message

      If the user clicks outside an element drags onto it and releases the button this is st ill countedas a mouseup event This sequence of act ions is not t reated as a button press in most userinterfaces so it is usually better to use the click event unless we know that the mouseup eventis preferable for a part icular situat ion

      Example 1 Show texts when mouseup and mousedown event t riggering

      Javascript

      $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

      HTML

      ltpgtPress mouse and release hereltpgt

      mousedown

      Bind an event handler to the mousedown JavaScript event or t rigger that event on anelement

      Added in version 10

      mousedown()jQuery

      This method is a shortcut for bind(mousedown handler) in the f irst variat ion andtrigger(mousedown) in the second

      The mousedown event is sent to an element when the mouse pointer is over the element andthe mouse button is pressed Any HTML element can receive this event

      For example consider the HTML

      ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

      The event handler can be boundto any ltdivgt

      $(target)mousedown(function() alert(Handler for mousedown() called))

      Now if we click on this element the alert is displayed

      Handler for mousedown() called

      We can also t rigger the event when a dif ferent element is clicked

      $(other)cl ick(function() $(target)mousedown())

      After this code executes clicks on Trigger the handler will also alert the message

      The mousedown event is sent when any mouse button is clicked To act only on specif icbuttons we can use the event object s which property Not all browsers support this property(Internet Explorer uses button instead) but jQuery normalizes the property so that it is safe touse in any browser The value of which will be 1 for the lef t but ton 2 for the middle button or 3for the right button

      This event is primarily useful for ensuring that the primary button was used to begin a dragoperat ion if ignored strange results can occur when the user at tempts to use a context menuWhile the middle and right buttons can be detected with these propert ies this is not reliable InOpera 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 st ill countedas a mousedown event This sequence of act ions is t reated as a canceling of the buttonpress in most user interfaces so it is usually better to use the click event unless we know thatthe mousedown event is preferable for a part icular situat ion

      Example 1 Show texts when mouseup and mousedown event t riggering

      Javascript

      $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

      HTML

      ltpgtPress mouse and release hereltpgt

      error

      Bind an event handler to the error JavaScript event

      Added in version 143

      error(eventData handler(eventObject))jQuery

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

      This method is a shortcut for bind(error handler)

      The error event is sent to elements such as images that are referenced by a document andloaded by the browser It is called if the element was not loaded correct ly

      For example consider a page with a simple image element

      ltimg alt=Book id=book gt

      The event handler can be bound to the image

      $(book) error(function() alert(Handler for error() called) ) attr(src missingpng)

      If the image cannot be loaded (for example because it is not present at the supplied URL) thealert is displayed

      Handler for error() called

      The event handler must be attached before the browser fires the error eventwhich is why the example sets the src attribute after attaching the handler Alsothe error event may not be correctly fired when the page is served locally errorrelies on HTTP status codes and will generally not be triggered if the URL usesthe file protocol

      Note A jQuery error event handler should not be at tached to the window object The browserf ires the windows error event when a script error occurs However the window error eventreceives dif ferent arguments and has dif ferent return value requirements than convent ionalevent handlers Use windowonerror instead

      Example 1 To hide the broken image icons for IE users you can try

      Javascript

      $(img) error(function() $(this)hide() ) attr(src missingpng)

      unload

      Bind an event handler to the unload JavaScript event

      Added in version 143

      unload(eventData handler(eventObject))jQuery

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

      This method is a shortcut for bind(unload handler)

      The unload event is sent to the window element when the user navigates away from the pageThis 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 t rigger the eventClosing the browser window will cause the event to be triggered Even a page reload will f irstcreate an unload event

      The exact handling of the unload event has varied from version to version ofbrowsers For example some versions of Firefox trigger the event when a link isfollowed but not when the window is closed In practical usage behavior shouldbe tested on all supported browsers and contrasted with the proprietarybeforeunload event

      Any unload event handler should be bound to the window object

      $(window)unload(function() alert(Handler for unload() called))

      After this code executes the alert will be displayed whenever the browser leaves the currentpage It is not possible to cancel the unload event with preventDefault () This event is availableso that scripts can perform cleanup when the user leaves the page

      Example 1 To display an alert when a page is unloaded

      Javascript

      $(window)unload( function () alert(Bye now) )

      load

      Bind an event handler to the load JavaScript event

      Added in version 143

      load(eventData handler(eventObject))jQuery

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

      This method is a shortcut for bind(load handler)

      The load 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 f ramesif rames and the window object

      For example consider a page with a simple image

      ltimg src=bookpng alt=Book id=book gt

      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 executedearlier it is usually best to place it in a handler sent to the ready() method

      The Ajax module also has a method named load() Which one is fired dependson the set of arguments passed

      Caveats of the load event when used with images

      A common challenge developers attempt to solve using the load() shortcut is toexecute a function when an image (or collection of images) have completelyloaded There are several known caveats with this that should be noted Theseare

      It doesnt work consistently nor reliably cross-browser

      It doesnt fire correctly in WebKit if the image src is set to the same src asbefore

      It doesnt correctly bubble up the DOM tree

      Can cease to fire for images that already live in the browsers cache

      Note The live() and delegate() methods cannot be used to detect the load eventof an iframe The load event does not correctly bubble up the parent documentand the eventtarget isnt set by Firefox IE9 or Chrome which is required to doevent delegation

      Note When calling load() using a URL without a suffixed selector expression the

      content is passed to html() prior to scripts being removed This executes the scriptblocks before they are discarded If load() is however called with a selectorexpression appended to the URL the scripts are stripped out prior to the DOMbeing updated which is why they are never executed An example of both casescan be seen below

      Here any JavaScript loaded into a as a part of the document will successfully execute

      $(a)load(articlehtml)

      However in this case script blocks in the document being loaded into b are stripped out priorto being executed

      $(b)load(articlehtml target)

      Example 1 Run a funct ion when the page is fully loaded including graphics

      Javascript

      $(window)load(function () run code)

      Example 2 Add the class bigImg to all images with height greater then 100 upon each imageload

      Javascript

      $( imguserIcon)load(function() if($(this)height() gt 100) $(this)addClass(bigImg) )

      ready

      Specify a funct ion to execute when the DOM is fully loaded

      Added in version 10

      ready(handler)jQuery

      handlerFunct ion A funct ion to execute af ter the DOM is ready

      While JavaScript provides the load event for execut ing code when a page is rendered thisevent does not get t riggered unt il all assets such as images have been completely received Inmost cases the script can be run as soon as the DOM hierarchy has been fully constructedThe handler passed to ready() is guaranteed to be executed af ter the DOM is ready so this isusually the best place to at tach all other event handlers and run other jQuery code When usingscripts that rely on the value of CSS style propert ies it s important to reference externalstylesheets or embed style elements before referencing the scripts

      In cases where code relies on loaded assets (for example if the dimensions of an image arerequired) the code should be placed in a handler for the load event instead

      The ready() method is generally incompatible with the ltbody onload=gtattribute If load must be used either do not use ready() or use jQuerys load()method to attach load event handlers to the window or to more specific items likeimages

      All three of the following syntaxes are equivalent

      $(document)ready(handler)

      $()ready(handler) (this is not recommended)

      $(handler)

      There is also $(document)bind(ready handler) This behaves similarly to the ready methodbut with one except ion If the ready event has already f ired and you try to bind(ready) thebound handler will not be executed Ready handlers bound this way are executed after anybound by the other three methods above

      The ready() method can only be called on a jQuery object matching the current document sothe selector can be omit ted

      The ready() method is typically used with an anonymous funct ion

      $(document)ready(function() Handler for ready() called)

      Which is equivalent to calling

      $(function() Handler for ready() called)

      If ready() is called af ter the DOM has been init ialized the new handler passed in will beexecuted immediately

      Aliasing the jQuery Namespace

      When using another JavaScript library we may wish to call $noConf lict () to avoid namespacedif f icult ies When this funct ion is called the $ shortcut is no longer available forcing us to writejQuery each t ime we would normally write $ However the handler passed to the ready()method can take an argument which is passed the global jQuery object This means we canrename the object within the context of our ready() handler without af fect ing other code

      jQuery(document)ready(function($) Code using $ as usual goes here)

      Example 1 Display a message when the DOM is loaded

      Javascript

      $(document)ready(function () $(p)text(The DOM is now loaded and can be manipulated))

      CSS

      p colorred

      HTML

      ltpgtNot loaded yetltpgt

      die

      Remove all event handlers previously at tached using live() f rom the elements

      Added in version 141

      die()jQuery

      Any handler that has been at tached with live() can be removed with die() This method isanalogous to calling unbind() with no arguments which is used to remove all handlers at tached

      with bind() See the discussions of live() and unbind() for further details

      Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

      die

      Remove an event handler previously at tached using live() f rom the elements

      Added in version 143

      die(eventTypes)jQuery

      eventTypesMap A map of one or more event types such as click or keydown and theircorresponding funct ions that are no longer to be executed

      Any handler that has been at tached with live() can be removed with die() This method isanalogous to unbind() which is used to remove handlers at tached with bind() See thediscussions of live() and unbind() for further details

      Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

      Example 1 Can bind and unbind events to the colored button

      Javascript

      function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(theone)l ive(click aClick) text(Can Click))$(unbind)cl ick(function () $(theone)die(click aClick) text(Does nothing))

      CSS

      button margin5px buttontheone colorred backgroundyellow

      HTML

      ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

      ltdiv style=displaynonegtClickltdivgt

      Example 2 To unbind all live events f rom all paragraphs write

      Javascript

      $(p)die()

      Example 3 To unbind all live click events f rom all paragraphs write

      Javascript

      $(p)die( cl ick )

      Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

      Javascript

      var foo = function () code to handle some kind of event

      $(p)l ive(click foo) now foo wil l be called when paragraphs are cl icked

      $(p)die(click foo) foo wil l no longer be called

      live

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

      Added in version 143

      live(events)jQuery

      eventsObject A map of one or more JavaScript event types and funct ions to executefor them

      This method is a variat ion on the basic bind() method for at taching event handlers to elementsWhen bind() is called the elements that the jQuery object refers to get the handler at tachedelements that get introduced later do not so they would require another bind() call Forinstance consider the HTML

      ltbodygt ltdiv class=clickmegt Click here ltdivgtltbodygt

      To bind a simple click handler to this element

      $(cl ickme)bind(cl ick function() Bound handler called)

      When the element is clicked the handler is called However suppose that af ter this anotherelement is added

      $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

      This new element also matches the selector clickme but since it was added af ter the call tobind() clicks on it will do nothing

      The live() method provides an alternat ive to this behavior To bind a click handler to the targetelement using this method

      $(cl ickme)l ive(cl ick function() Live handler called)

      And then later add a new element

      $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

      Then clicks on the new element will also t rigger the handler

      To unbind the click handlers f rom all ltdiv class=clickmegt that were bound using live() use thedie() method

      $(cl ickme)die(click)

      Event Delegation

      The live() method is able to af fect elements that have not yet been added to the DOM throughthe use of event delegat ion a handler bound to an ancestor element is responsible for eventsthat are t riggered on its descendants The handler passed to live() is never bound to anelement instead live() binds a special handler to the root of the DOM tree In the exampleabove when the new element is clicked the following steps occur

      1 A click event is generated and passed to the ltdivgt for handling

      2 No handler is direct ly bound to the ltdivgt so the event bubbles up the DOM tree

      3 The event bubbles up unt il it reaches the root of the t ree which is where live() binds itsspecial handlers by default

      As of jQuery 14 event bubbling can optionally stop at a DOM element context

      4 The special click handler bound by live() executes

      5 This handler tests the target of the event object to see whether it should cont inue Thistest is performed by checking if $(eventtarget)closest(clickme) is able to locate amatching element

      6 If a matching element is found the original handler is called on it

      Because the test in step 5 is not performed unt il the event occurs elements can be added atany t ime and st ill respond to events

      See the discussion for bind() for more informat ion on event binding

      Multiple Events

      As of jQuery 141 live() can accept mult iple space-separated events similar to thefunct ionality provided in bind() For example you can live bind the mouseover and mouseoutevents at the same t ime like so

      $(hoverme)l ive(mouseover mouseout function(event) if ( eventtype == mouseover ) do something on mouseover else do something on mouseout )

      As of jQuery 143 you can bind mult iple live event handlers simultaneously by passing a map ofevent typehandler pairs

      $(a)l ive( cl ick function() do something on click mouseover function() do something on mouseover )

      Event Data

      As of jQuery 14 the opt ional eventData parameter is available for passing addit ionalinformat ion to the handler One handy use of this parameter is to work around issues causedby closures See the bind() methods Passing Event Data discussion for more informat ion

      Event Context

      As of jQuery 14 live events can be bound to a DOM element context rather than to thedefault document root To set this context use the jQuery() funct ions second argumentpassing in a single DOM element (as opposed to a jQuery collect ion or a selector)

      $(divcl ickme $(container)[0])l ive(click function() Live handler called)

      The live handler in this example is called only when ltdiv class=clickmegt is a descendant of anelement with an ID of container

      Caveats

      The live() technique is useful but due to its special approach cannot be simply subst ituted forbind() in all cases Specif ic dif ferences include

      DOM traversal methods are not supported for f inding elements to send to live()Rather the live() method should always be called direct ly af ter a selector as in theexample above

      To stop further handlers f rom execut ing af ter one bound using live() the handler mustreturn false Calling stopPropagat ion() will not accomplish this

      The paste and reset events in addit ion to change when used with inputs of type f ileare not fully supported by the live() method due to issues with simulat ing event bubblingin Internet Explorer In these cases the bind() method can be used instead

      In jQuery 13x only the following JavaScript events (in addit ion to custom events)could be bound with live() click dblclick keydown keypress keyup mousedown

      mousemove mouseout mouseover and mouseup

      As of jQuery 14 the live() method supports custom events as well as allJavaScript events that bubble

      As of jQuery 141 even focus and blur work with live (mapping to themore appropriate bubbling events focusin and focusout)

      As of jQuery 141 the hover event can be specified (mapping tomouseenter and mouseleave which in turn are mapped to mouseover andmouseout)

      Example 1 Click a paragraph to add another Note that live() binds the click event to allparagraphs - even new ones

      Javascript

      $(p)l ive(click function() $(this)after(ltpgtAnother paragraphltpgt))

      CSS

      p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

      HTML

      ltpgtClick meltpgt

      ltspangtltspangt

      Example 2 Cancel a default act ion and prevent it f rom bubbling up by returning false

      Javascript

      $(a)l ive(click function() return false )

      Example 3 Cancel only the default act ion by using the preventDefault method

      Javascript

      $(a)l ive(click function(event) eventpreventDefault())

      Example 4 Bind custom events with live()

      Javascript

      $(p)l ive(myCustomEvent function(e myName myValue) $(this)text(Hi there) $(span)stop()css(opacity 1) text(myName = + myName) fadeIn(30)fadeOut(1000))$(button)cl ick(function () $(p)trigger(myCustomEvent))

      CSS

      p colorred span colorblue

      HTML

      ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

      Example 5 Use a map to bind mult iple live event handlers Note that live() binds the clickmouseover and mouseout events to all paragraphs acirceurordquo even new ones

      Javascript

      $(p)l ive( cl ick function() $(this)after(ltpgtAnother paragraphltpgt) mouseover function() $(this)addClass(over) mouseout function() $(this)removeClass(over) )

      CSS

      p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

      HTML

      ltpgtClick meltpgt ltspangtltspangt

      triggerHandler

      Execute all handlers at tached to an element for an event

      Added in version 12

      triggerHandler(eventType extraParameters)Object

      eventTypeString A string containing a JavaScript event type such as click orsubmit

      extraParametersArray An array of addit ional parameters to pass along to the eventhandler

      The t riggerHandler() method behaves similarly to t rigger() with the following except ions

      The t riggerHandler() method does not cause the default behavior of an event to occur(such as a form submission)

      While t rigger() will operate on all elements matched by the jQuery object t riggerHandler() only af fects the f irst matched element

      Events created with t riggerHandler() do not bubble up the DOM hierarchy if they arenot handled by the target element direct ly they do nothing

      Instead of returning the jQuery object (to allow chaining) t riggerHandler() returnswhatever value was returned by the last handler it caused to be executed If no handlersare t riggered it returns undef ined

      For more informat ion on this method see the discussion for t rigger()

      Example 1 If you called t riggerHandler() on a focus event - the browsers default focus act ionwould not be triggered only the event handlers bound to the focus event

      Javascript

      $(old)cl ick(function()$(input)trigger(focus))$(new)cl ick(function()$(input)triggerHandler(focus))$(input)focus(function()$(ltspangtFocusedltspangt)appendTo(body)fadeOut(1000))

      HTML

      ltbutton id=oldgttrigger(focus)ltbuttongtltbutton id=newgttriggerHandler(focus)ltbuttongtltbrgtltbrgt

      ltinput type=text value=To Be Focusedgt

      trigger

      Execute all handlers and behaviors at tached to the matched elements for the given event type

      Added in version 13

      trigger(event)jQuery

      eventEvent A jQueryEvent object

      Any event handlers at tached with bind() or one of its shortcut methods are t riggered when thecorresponding event occurs They can be f ired manually however with the t rigger() method Acall to t rigger() executes the handlers in the same order they would be if the event weretriggered naturally by the user

      $(foo)bind(cl ick function() alert($(this)text()) ) $(foo)trigger(cl ick)

      As of jQuery 13 t rigger()ed events bubble up the DOM tree an event handler can stop thebubbling by returning false f rom the handler or calling the stopPropagat ion() method on theevent object passed into the event Although t rigger() simulates an event act ivat ion completewith a synthesized event object it does not perfect ly replicate a naturally-occurring event

      To trigger handlers bound via jQuery without also t riggering the nat ive event use

      t riggerHandler() instead

      When we def ine a custom event type using the bind() method the second argument tot rigger() can become useful For example suppose we have bound a handler for the customevent to our element instead of the built -in click 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 f irst parameter to an event handler but if addit ionalparameters are specif ied during a t rigger() call these parameters will be passed along to thehandler as well To pass more than one parameter use an array as shown here As of jQuery162 a single parameter can be passed without using an array

      Note the dif ference between the extra parameters were passing here and the eventDataparameter to the bind() method Both are mechanisms for passing informat ion to an eventhandler but the extraParameters argument to t rigger() allows informat ion to be determined atthe t ime the event is t riggered while the eventData argument to bind() requires the informat ionto be already computed at the t ime the handler is bound

      Example 1 Clicks to button 2 also t rigger a click for button 1

      Javascript

      $(buttonfirst)cl ick(function () update($(spanfirst)))$(buttonlast)cl ick(function () $(buttonfirst)trigger(cl ick)

      update($(spanlast)))

      function update(j) var n = parseInt(jtext() 10)j text(n + 1)

      CSS

      button margin10px div colorblue font-weightbold span colorred

      HTML

      ltbuttongtButton 1ltbuttongtltbuttongtButton 2ltbuttongtltdivgtltspangt0ltspangt button 1 clicksltdivgt

      ltdivgtltspangt0ltspangt button 2 clicksltdivgt

      Example 2 To submit the f irst form without using the submit() funct ion t ry

      Javascript

      $(formfirst)trigger(submit)

      Example 3 To submit the f irst form without using the submit() funct ion t ry

      Javascript

      var event = jQueryEvent(submit)$(formfirst)trigger(event)if ( eventisDefaultPrevented() ) Perform an action

      Example 4 To pass arbit rary data to an event

      Javascript

      $(p)cl ick( function (event a b) when a normal cl ick fires a and b are undefined for a trigger l ike below a refers to foo and b refers to bar

      )trigger(click [foo bar])

      Example 5 To pass arbit rary data through an event object

      Javascript

      var event = jQueryEvent(logged)eventuser = fooeventpass = bar$(body)trigger(event)

      Example 6 Alternat ive way to pass data through an event object

      Javascript

      $(body)trigger(typeloggeduserfoopassbar

      )

      one

      Attach a handler to an event for the elements The handler is executed at most once perelement

      Added in version 11

      one(eventType eventData handler(eventObject))jQuery

      eventTypeString A string containing one or more JavaScript event typessuch as click or submit or custom event names

      eventDataObject (opt ional) A map of data that will be passed to theevent handler

      handler(eventObject)Funct ion A funct ion to execute at the t ime the event is t riggered

      This method is ident ical to bind() except that the handler is unbound af ter its f irst invocat ionFor example

      $(foo)one(click function() alert(This wil l be displayed only once))

      After the code is executed a click on the element with ID foo will display the alert Subsequentclicks will do nothing This code is equivalent to

      $(foo)bind(click function( event ) alert(This wil l be displayed only once) $(this)unbind( event ))

      In other words explicit ly calling unbind() f rom within a regularly-bound handler has exact ly thesame effect

      If the f irst argument contains more than one space-separated event types the event handler is

      called once for each event type

      Example 1 Tie a one-t ime click to each div

      Javascript

      var n = 0$(div)one(click function() var index = $(div)index(this) $(this)css( borderStyleinset cursorauto ) $(p)text(Div at index + index + cl icked + Thats + ++n + total cl icks))

      CSS

      div width60px height60px margin5px floatleftbackgroundgreen border10px outset cursorpointer p colorred margin0 clearleft

      HTML

      ltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

      ltpgtClick a green squareltpgt

      Example 2 To display the text of all paragraphs in an alert box the f irst t ime each of them isclicked

      Javascript

      $(p)one(click function()alert( $(this)text() ))

      unbind

      Remove a previously-at tached event handler f rom the elements

      Added in version 10

      unbind(event)jQuery

      eventObject A JavaScript event object as passed to an event handler

      Any handler that has been at tached with bind() can be removed with unbind() In the simplestcase with no arguments unbind() removes all handlers at tached to the elements

      $(foo)unbind()

      This version removes the handlers regardless of type To be more precise we can pass anevent type

      $(foo)unbind(cl ick)

      By specifying the click event type only handlers for that event type will be unbound Thisapproach can st ill have negat ive ramif icat ions if other scripts might be at taching behaviors tothe same element however Robust and extensible applicat ions typically demand the two-argument version for this reason

      var handler = function() alert(The quick brown fox jumps over the lazy dog)$(foo)bind(cl ick handler)$(foo)unbind(cl ick handler)

      By naming the handler we can be assured that no other funct ions are caught in the crossf ireNote that the following will not work

      $(foo)bind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

      wil l NOT work$(foo)unbind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

      Even though the two funct ions are ident ical in content they are created separately and soJavaScript is f ree to keep them as dist inct funct ion objects To unbind a part icular handler weneed a reference to that funct ion and not a dif ferent one that happens to do the same thing

      Note Because the live() method binds event handlers to document by defaultcalling unbind() on document will unbind the handlers bound by live() as wellFor example $(document)unbind(click) will remove not only$(document)bind(click fn1)

      but also

      $(afoo)live(click fn2)

      Note Using a proxied function to unbind an event on an element will unbind allproxied functions on that element as the same proxy function is used for allproxied events To allow unbinding a specific event use unique class names onthe event (eg clickproxy1 clickproxy2) when attaching them

      Using Namespaces

      Instead of maintaining references to handlers in order to unbind them we can namespace theevents and use this capability to narrow the scope of our unbinding act ions As shown in thediscussion for the bind() method namespaces are def ined by using a period () character whenbinding a handler

      $(foo)bind(cl ickmyEvents handler)

      When a handler is bound in this fashion we can st ill unbind it the normal way

      $(foo)unbind(cl ick)

      However if we want to avoid af fect ing other handlers we can be more specif ic

      $(foo)unbind(cl ickmyEvents)

      We can also unbind all of the handlers in a namespace regardless of event type

      $(foo)unbind(myEvents)

      It is part icularly useful to at tach namespaces to event bindings when we are developing plug-insor otherwise writ ing code that may interact with other event-handling code in the future

      Using the Event Object

      The third form of the unbind() method is used when we wish to unbind a handler f rom withinitself For example suppose we wish to t rigger an event handler only three t imes

      var timesClicked = 0$(foo)bind(cl ick function(event) alert(The quick brown fox jumps over the lazy dog) timesClicked++ if (timesClicked gt= 3) $(this)unbind(event) )

      The handler in this case must take a parameter so that we can capture the event object anduse it to unbind the handler af ter the third click The event object contains the contextnecessary for unbind() to know which handler to remove This example is also an illustrat ion ofa closure Since the handler refers to the t imesClicked variable which is def ined outside thefunct ion increment ing the variable has an ef fect even between invocat ions of the handler

      Example 1 Can bind and unbind events to the colored button

      Javascript

      function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () could use bind(cl ick aClick) instead but for variety$(theone)cl ick(aClick) text(Can Click))$(unbind)cl ick(function () $(theone)unbind(cl ick aClick) text(Does nothing))

      CSS

      button margin5px buttontheone colorred backgroundyellow

      HTML

      ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

      ltdiv style=displaynonegtClickltdivgt

      Example 2 To unbind all events f rom all paragraphs write

      Javascript

      $(p)unbind()

      Example 3 To unbind all click events f rom all paragraphs write

      Javascript

      $(p)unbind( cl ick )

      Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

      Javascript

      var foo = function () code to handle some kind of event

      $(p)bind(click foo) now foo wil l be called when paragraphs are cl icked

      $(p)unbind(click foo) foo wil l no longer be called

      bind

      Attach a handler to an event for the elements

      Added in version 14

      bind(events)jQuery

      eventsObject A map of one or more JavaScript event types and funct ions to executefor them

      The bind() method is the primary means of at taching behavior to a document All JavaScriptevent types such as focus mouseover and resize are allowed for eventType The error eventon the window object uses nonstandard convent ions and is not supported by jQuery at tach ahandler direct ly to the window object instead The beforeunload event is supported cross-browser in jQuery 151 and 16+ but is not supported in IE for jQuery 152 due to a regression

      The jQuery library provides shortcut methods for binding the standard event types such asclick() for bind(click) A descript ion of each can be found in the discussion of its shortcutmethod blur focus focusin focusout load resize scroll unload click dblclick mousedownmouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error

      Any string is legal for eventType if the string is not the name of a nat ive JavaScript event thenthe handler is bound to a custom event These events are never called by the browser but maybe triggered manually f rom other JavaScript code using t rigger() or t riggerHandler()

      If the eventType string contains a period () character then the event is namespaced Theperiod character separates the event f rom its namespace For example in the callbind(clickname handler) the string click is the event type and the string name is thenamespace Namespacing allows us to unbind or t rigger some events of a type withoutaf fect ing others See the discussion of unbind() for more informat ion

      When an event reaches an element all handlers bound to that event type for the element aref ired If there are mult iple handlers registered they will always execute in the order in which theywere bound After all handlers have executed the event cont inues along the normal eventpropagat ion path

      A basic usage of bind() is

      $(foo)bind(cl ick function() alert(User cl icked on foo))

      This code will cause the element with an ID of foo to respond to the click event When a userclicks inside this element thereafter the alert will be shown

      Multiple Events

      Mult iple event types can be bound at once by including each one separated by a space

      $(foo)bind(mouseenter mouseleave function() $(this)toggleClass(entered))

      The ef fect of this on ltdiv id=foogt (when it does not init ially have the entered class) is toadd the entered class when the mouse enters the ltdivgt and remove the class when themouse leaves

      As of jQuery 14 we can bind mult iple event handlers simultaneously by passing a map of eventtypehandler pairs

      $(foo)bind( cl ick function() do something on click mouseenter function() do something on mouseenter )

      Event Handlers

      The handler parameter takes a callback funct ion as shown above Within the handler thekeyword this refers to the DOM element to which the handler is bound To make use of theelement in jQuery it can be passed to the normal $() funct ion For example

      $(foo)bind(cl ick function() alert($(this)text()))

      After this code is executed when the user clicks inside the element with an ID of foo its textcontents will be shown as an alert

      As of jQuery 142 duplicate event handlers can be bound to an element instead of beingdiscarded For example

      function test() alert(Hello) $(button)cl ick( test )$(button)cl ick( test )

      The above will generate two alerts when the button is clicked

      In jQuery 143 you can now pass in false in place of an event handler This will bind an eventhandler that s equivalent to funct ion() return false This funct ion can be removed at a latert ime by calling unbind( eventName false )

      The Event object

      The handler callback funct ion can also take parameters When the funct ion is called theJavaScript event object will be passed to the f irst parameter

      The event object is of ten unnecessary and the parameter omit ted as suff icient context isusually available when the handler is bound to know exact ly what needs to be done when thehandler is t riggered However at t imes it becomes necessary to gather more informat ion aboutthe users environment at the t ime the event was init iated View the full Event Object

      Returning false f rom a handler is equivalent to calling both preventDefault () andstopPropagat ion() on the event object

      Using the event object in a handler looks like this

      $(document)ready(function() $(foo)bind(cl ick function(event) alert(The mouse cursor is at ( + eventpageX + + eventpageY + )) ))

      Note the parameter added to the anonymous funct ion This code will cause a click on theelement with ID foo to report the page coordinates of the mouse cursor at the t ime of the click

      Passing Event Data

      The opt ional eventData parameter is not commonly used When provided this argument allowsus to pass addit ional informat ion to the handler One handy use of this parameter is to workaround issues caused by closures For example suppose we have two event handlers that bothrefer to the same external variable

      var message = Spoon$(foo)bind(cl ick function() alert(message))message = Not in the face$(bar)bind(cl ick function() alert(message))

      Because the handlers are closures that both have message in their environment both willdisplay the message Not in the face when triggered The variables value has changed Tosidestep this we can pass the message in using eventData

      var message = Spoon$(foo)bind(cl ick msg message function(event) alert(eventdatamsg))message = Not in the face$(bar)bind(cl ick msg message function(event) alert(eventdatamsg))

      This t ime the variable is not referred to direct ly within the handlers instead the variable is

      passed in by value through eventData which f ixes the value at the t ime the event is boundThe f irst handler will now display Spoon while the second will alert Not in the face

      Note that objects are passed to functions by reference which further complicatesthis scenario

      If eventData is present it is the second argument to the bind() method if no addit ional dataneeds to be sent to the handler then the callback is passed as the second and f inal argument

      See the trigger() method reference for a way to pass data to a handler at the timethe event happens rather than when the handler is bound

      As of jQuery 14 we can no longer at tach data (and thus events) to object embed or appletelements because crit ical errors occur when at taching data to Java applets

      Note Although demonstrated in the next example it is inadvisable to bind handlers to both theclick and dblclick events for the same element The sequence of events t riggered varies f rombrowser to browser with some receiving two click events before the dblclick and others onlyone Double-click sensit ivity (maximum t ime between clicks that is detected as a double click)can vary by operat ing system and browser and is of ten user-conf igurable

      Example 1 Handle click and double-click for the paragraph Note the coordinates are windowrelat ive so in this case relat ive to the demo if rame

      Javascript

      $(p)bind(click function(event)var str = ( + eventpageX + + eventpageY + )$(span)text(Click happened + str))$(p)bind(dblcl ick function()$(span)text(Double-click happened in + thisnodeName))$(p)bind(mouseenter mouseleave function(event)$(this)toggleClass(over))

      CSS

      p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

      HTML

      ltpgtClick or double cl ick hereltpgtltspangtltspangt

      Example 2 To display each paragraphs text in an alert box whenever it is clicked

      Javascript

      $(p)bind(click function()alert( $(this)text() ))

      Example 3 You can pass some extra data before the event handler

      Javascript

      function handler(event) alert(eventdatafoo)$(p)bind(click foo bar handler)

      Example 4 Cancel a default act ion and prevent it f rom bubbling up by returning false

      Javascript

      $(form)bind(submit function() return false )

      Example 5 Cancel only the default act ion by using the preventDefault () method

      Javascript

      $(form)bind(submit function(event) eventpreventDefault())

      Example 6 Stop an event f rom bubbling without prevent ing the default act ion by using thestopPropagat ion() method

      Javascript

      $(form)bind(submit function(event) eventstopPropagation())

      Example 7 Bind custom events

      Javascript

      $(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)cl ick(function () $(p)trigger(myCustomEvent [ John ]))

      CSS

      p colorred span colorblue

      HTML

      ltpgtHas an attached custom eventltpgtltbuttongtTrigger custom eventltbuttongtltspan style=displaynonegtltspangt

      Example 8 Bind mult iple events simultaneously

      Javascript

      $(divtest)bind( cl ick function() $(this)addClass(active) mouseenter function() $(this)addClass(inside) mouseleave function() $(this)removeClass(inside) )

      Deferred Object

      deferredpipe

      Utility method to f ilter andor chain Deferreds

      Added in version 16

      deferredpipe(doneFilter failFilter)Promise

      doneFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isresolved

      failFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isrejected

      The deferredpipe() method returns a new promise that f ilters the status and values of adeferred through a funct ion The doneFilter and failFilter funct ions f ilter the original deferredsresolved rejected status and values These f ilter funct ions can return a new value to bepassed along to the piped promises done() or fail() callbacks or they can return anotherobservable object (Deferred Promise etc) which will pass its resolved rejected status andvalues to the piped promises callbacks If the f ilter funct ion used is null or not specif ied thepiped promise will be resolved or rejected with the same values as the original

      Example 1 Filter resolve value

      Javascript

      var defer = $Deferred() fi ltered = deferpipe(function( value ) return value 2 )

      deferresolve( 5 )fi ltereddone(function( value ) alert( Value is ( 25 = ) 10 + value ))

      Example 2 Filter reject value

      Javascript

      var defer = $Deferred() fi ltered = deferpipe( null function( value ) return value 3 )

      deferreject( 6 )fi lteredfail(function( value ) alert( Value is ( 36 = ) 18 + value ))

      Example 3 Chain tasks

      Javascript

      var request = $ajax( url dataType json ) chained = requestpipe(function( data ) return $ajax( url2 data user datauserId ) )

      chaineddone(function( data ) data retrieved from url2 as provided by the first request)

      deferredalways

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

      Added in version 16

      deferredalways(alwaysCallbacks)Deferred

      alwaysCallbacksFunct ion A funct ion or array of funct ions that is called when theDeferred is resolved or rejected

      The argument can be either a single funct ion or an array of funct ions When the Deferred isresolved or rejected the alwaysCallbacks are called Since deferredalways() returns theDeferred object other methods of the Deferred object can be chained to this one includingaddit ional always() methods When the Deferred is resolved or rejected callbacks are executedin the order they were added using the arguments provided to the resolve reject resolveWithor rejectWith method calls For more informat ion see the documentat ion for Deferred object

      Example 1 Since the jQueryget() method returns a jqXHR object which is derived from aDeferred object we can at tach a callback for both success and error using thedeferredalways() method

      Javascript

      $get(testphp)always( function() alert($get completed with success or error callback arguments) )

      promise

      Return a Promise object to observe when all act ions of a certain type bound to the collect ionqueued or not have f inished

      Added in version 16

      promise(type target)Promise

      typeString (opt ional) The type of queue that needs to be observed

      targetObject (opt ional) Object onto which the promise methods have to be at tached

      The promise() method returns a dynamically generated Promise that is resolved once allact ions of a certain type bound to the collect ion queued or not have ended

      By default type is fx which means the returned Promise is resolved when all animat ions ofthe selected elements have completed

      Resolve context and sole argument is the collect ion onto which promise() has been called

      If target is provided promise() will at tach the methods onto it and then return this object ratherthan create a new one This can be useful to at tach the Promise behavior to an object thatalready exists

      Note The returned Promise is linked to a Deferred object stored on the data() foran element Since the remove() method removes the elements data as well asthe element itself it will prevent any of the elements unresolved Promises fromresolving If it is necessary to remove an element from the DOM before its Promiseis resolved use detach() instead and follow with removeData() after resolution

      Example 1 Using promise() on a collect ion with no act ive animat ion returns a resolved Promise

      Javascript

      var div = $( ltdiv gt )

      divpromise()done(function( arg1 ) wil l fire right away and alert true alert( this === div ampamp arg1 === div ))

      Example 2 Resolve the returned Promise when all animat ions have ended (including thoseinit iated in the animat ion callback or added later on)

      CSS

      div height 50px width 50px float left margin-right 10px display none background-color 090

      HTML

      ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

      Javascript

      $(button)bind( cl ick function() $(p)append( Started) $(div)each(function( i ) $( this )fadeIn()fadeOut( 1000 (i+1) ) )

      $( div )promise()done(function() $( p )append( Finished ) ))

      Example 3 Resolve the returned Promise using a $when() statement (the promise() methodmakes it possible to do this with jQuery collect ions)

      CSS

      div height 50px width 50px float left margin-right 10px display none background-color 090

      HTML

      ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

      Javascript

      var effect = function() return $(div)fadeIn(800)delay(1200)fadeOut()

      $(button)bind( cl ick function() $(p)append( Started )

      $when( effect() )done(function() $(p)append( Finished ) ))

      deferredpromise

      Return a Deferreds Promise object

      Added in version 15

      deferredpromise(target)Promise

      targetObject (opt ional) Object onto which the promise methods have to be at tached

      The deferredpromise() method allows an asynchronous funct ion to prevent other code frominterfering with the progress or status of its internal request The Promise exposes only theDeferred methods needed to at tach addit ional handlers or determine the state (then done failisResolved and isRejected) but not ones that change the state (resolve reject resolveWithand rejectWith) As of jQuery 16 the Promise also exposes the always and pipe Deferredmethods

      If target is provided deferredpromise() will at tach the methods onto it and then return thisobject rather than create a new one This can be useful to at tach the Promise behavior to anobject that already exists

      If you are creat ing a Deferred keep a reference to the Deferred so that it can be resolved orrejected at some point Return only the Promise object via deferredpromise() so other codecan register callbacks or inspect the current state

      For more informat ion see the documentat ion for Deferred object

      Example 1 Create a Deferred and set two t imer-based funct ions to either resolve or reject theDeferred af ter a random interval Whichever one f ires f irst wins and will call one of thecallbacks The second t imeout has no ef fect since the Deferred is already complete (in aresolved or rejected state) f rom the f irst t imeout act ion

      Javascript

      Create a Deferred and return its Promisefunction asyncEvent() var dfd = new jQueryDeferred() setTimeout(function() dfdresolve(hurray) Mathfloor(Mathrandom()1500)) setTimeout(function() dfdreject(sorry) Mathfloor(Mathrandom()1500)) return dfdpromise()

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

      Example 2 Use the target argument to promote an exist ing object to a Promise

      Javascript

      Existing objectvar obj = hello function( name ) alert( Hello + name ) Create a Deferreddefer = $Deferred()

      Set object as a promisedeferpromise( obj )

      Resolve the deferreddeferresolve( John )

      Use the object as a Promiseobjdone(function( name ) objhello( name ) wil l alert Hello John)hello( Karl ) wil l alert Hello Karl

      jQuerywhen see Core

      deferredresolveWith

      Resolve a Deferred object and call any doneCallbacks with the given context and args

      Added in version 15

      deferredresolveWith(context args)Deferred

      context Object Context passed to the doneCallbacks as the this object

      argsArray (opt ional) An opt ional array of arguments that are passed to thedoneCallbacks

      Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

      When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

      deferredrejectWith

      Reject a Deferred object and call any failCallbacks with the given context and args

      Added in version 15

      deferredrejectWith(context args)Deferred

      context Object Context passed to the failCallbacks as the this object

      argsArray (opt ional) An opt ional array of arguments that are passed to thefailCallbacks

      Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

      When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

      deferredfail

      Add handlers to be called when the Deferred object is rejected

      Added in version 15

      deferredfail(failCallbacks failCallbacks)Deferred

      failCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is rejected

      failCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is rejected

      The deferredfail() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is rejected the failCallbacks are calledCallbacks are executed in the order they were added Since deferredfail() returns the deferredobject other methods of the deferred object can be chained to this one including addit ionaldeferredfail() methods The failCallbacks are executed using the arguments provided to thedeferredreject() or deferredrejectWith() method call in the order they were added For moreinformat ion see the documentat ion for Deferred object

      Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred you can at tach a success and failure callback using the deferreddone() anddeferredfail() methods

      Javascript

      $get(testphp) done(function() alert($get succeeded) ) fai l(function() alert($get fai led) )

      deferreddone

      Add handlers to be called when the Deferred object is resolved

      Added in version 15

      deferreddone(doneCallbacks doneCallbacks)Deferred

      doneCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is resolved

      doneCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is resolved

      The deferreddone() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is resolved the doneCallbacks are calledCallbacks are executed in the order they were added Since deferreddone() returns thedeferred object other methods of the deferred object can be chained to this one includingaddit ional done() methods When the Deferred is resolved doneCallbacks are executed usingthe arguments provided to the resolve or resolveWith method call in the order they were addedFor more informat ion see the documentat ion for Deferred object

      Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach a success callback using the done() method

      Javascript

      $get(testphp)done(function() alert($get succeeded) )

      Example 2 Resolve a Deferred object when the user clicks a button t riggering a number ofcallback funct ions

      Javascript

      3 functions to call when the Deferred object is resolvedfunction fn1() $(p)append( 1 )function fn2() $(p)append( 2 )function fn3(n) $(p)append(n + 3 + n)

      create a deferred objectvar dfd = $Deferred()

      add handlers to be called when dfd is resolveddfd done() can take any number of functions or arrays of functionsdone( [fn1 fn2] fn3 [fn2 fn1] ) we can chain done methods toodone(function(n) $(p)append(n + were done))

      resolve the Deferred object when the button is cl icked$(button)bind(click function() dfdresolve(and))

      HTML

      ltbuttongtGoltbuttongt ltpgtReadyltpgt

      deferredthen

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

      Added in version 15

      deferredthen(doneCallbacks failCallbacks)Deferred

      doneCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isresolved

      failCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isrejected

      Both arguments can be either a single funct ion or an array of funct ions Either argument can

      also be null if no callback of that type is desired Alternat ively use done() or fail() to set onlydoneCallbacks or failCallbacks When the Deferred is resolved the doneCallbacks are called Ifthe Deferred is instead rejected the failCallbacks are called Callbacks are executed in the orderthey were added Since deferredthen returns the deferred object other methods of thedeferred object can be chained to this one including addit ional then() methods For moreinformat ion see the documentat ion for Deferred object

      Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach handlers using the then method

      Javascript

      $get(testphp)then( function() alert($get succeeded) function() alert($get fai led) )

      deferredreject

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

      Added in version 15

      deferredreject(args)Deferred

      argsObject Opt ional arguments that are passed to the failCallbacks

      Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

      When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

      deferredisRejected

      Determine whether a Deferred object has been rejected

      Added in version 15

      deferredisRejected()Boolean

      Returns t rue if the Deferred object is in the rejected state meaning that either deferredreject()

      or deferredrejectWith() has been called for the object and the failCallbacks have been called (orare in the process of being called)

      Note that a Deferred object can be in one of three states unresolved resolved or rejecteduse deferredisResolved() to determine whether the Deferred object is in the resolved stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

      deferredisResolved

      Determine whether a Deferred object has been resolved

      Added in version 15

      deferredisResolved()Boolean

      Returns t rue if the Deferred object is in the resolved state meaning that eitherdeferredresolve() or deferredresolveWith() has been called for the object and thedoneCallbacks 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 rejecteduse deferredisRejected() to determine whether the Deferred object is in the rejected stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

      deferredresolve

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

      Added in version 15

      deferredresolve(args)Deferred

      argsObject Opt ional arguments that are passed to the doneCallbacks

      When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

      Effects

      fadeToggle

      Display or hide the matched elements by animat ing their opacity

      Added in version 144

      fadeToggle(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackFunct ion (opt ional) A funct ion to call once the animat ion is complete

      The fadeToggle() method animates the opacity of the matched elements When called on avisible element the element s display style property is set to none once the opacity reaches 0so the element no longer af fects the layout of the page

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      Easing

      The string represent ing an easing funct ion specif ies the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easing implementat ions in thejQuery library are the default called swing and one that progresses at a constant pace calledlinear More easing funct ions are available with the use of plug-ins most notably the jQuery UIsuite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

      As of jQuery 16 the promise() method can be used in conjunct ion with the deferreddone()method to execute a single callback for the animat ion as a whole when all matching elementshave completed their animat ions ( See the example for promise() )

      Example 1 Fades f irst paragraph in or out complet ing the animat ion within 600 millisecondsand using a linear easing Fades last paragraph in or out for 200 milliseconds insert ing af inished message upon complet ion

      Javascript

      $(buttonfirst)cl ick(function() $(pfirst)fadeToggle(slow l inear))$(buttonlast)cl ick(function () $(plast)fadeToggle(fast function () $(log)append(ltdivgtfinishedltdivgt) ))

      HTML

      ltbuttongtfadeToggle p1ltbuttongtltbuttongtfadeToggle p2ltbuttongtltpgtThis paragraph has a slow l inear fadeltpgt

      ltpgtThis paragraph has a fast animationltpgtltdiv id=loggtltdivgt

      jQueryfxinterval

      The rate (in milliseconds) at which animat ions f ire

      Added in version 143

      This property can be manipulated to adjust the number of f rames per second at whichanimat ions will run The default is 13 milliseconds Making this a lower number could make theanimat ions run smoother in faster browsers (such as Chrome) but there may be performanceand CPU implicat ions of doing so

      Since jQuery uses one global interval no animat ion should be running or all animat ions shouldstop for the change of this property to take ef fect

      NotejQueryfxinterval current ly has no ef fect in browsers that support therequestAnimat ionFrame property such as Google Chrome 11 This behavior is subject tochange in a future release

      Example 1 Cause all animat ions to run with less f rames

      Javascript

      jQueryfxinterval = 100

      $(input)cl ick(function() $(div)toggle( 3000 ))

      CSS

      div width50px height30px margin5px floatleft backgroundgreen

      HTML

      ltpgtltinput type=button value=Rungtltpgtltdivgtltdivgt

      delay

      Set a t imer to delay execut ion of subsequent items in the queue

      Added in version 14

      delay(durat ion queueName)jQuery

      durat ionInteger An integer indicat ing the number of milliseconds to delay execut ionof the next item in the queue

      queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

      Added to jQuery in version 14 the delay() method allows us to delay the execut ion offunct ions that follow it in the queue It can be used with the standard ef fects queue or with acustom queue Only subsequent events in a queue are delayed for example this will not delaythe no-arguments forms of show() or hide() which do not use the ef fects queue

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      Using the standard ef fects queue we can for example set an 800-millisecond delay betweenthe slideUp() and fadeIn() of ltdiv id=foogt

      $(foo)sl ideUp(300)delay(800)fadeIn(400)

      When this statement is executed the element slides up for 300 milliseconds and then pausesfor 800 milliseconds before fading in for 400 milliseconds

      The delay() method is best for delaying between queued jQuery effects Because

      it is limitedacirceurordquoit doesnt for example offer a way to cancel the delayacirceurordquodelay() isnot a replacement for JavaScripts native setTimeout function which may be moreappropriate for certain use cases

      Example 1 Animate the hiding and showing of two divs delaying the f irst before showing it

      CSS

      div position absolute width 60px height 60px float left first background-color 3f3 left 0second background-color 33f left 80px

      Javascript

      $(button)cl ick(function() $(divfirst)sl ideUp(300)delay(800)fadeIn(400) $(divsecond)sl ideUp(300)fadeIn(400) )

      HTML

      ltpgtltbuttongtRunltbuttongtltpgtltdiv class=firstgtltdivgtltdiv class=secondgtltdivgt

      jQueryfxoff

      Globally disable all animat ions

      Added in version 13

      When this property is set to t rue all animat ion methods will immediately set elements to theirf inal state when called rather than displaying an ef fect This may be desirable for a couplereasons

      jQuery is being used on a low-resource device

      Users are encountering accessibility problems with the animat ions (see the art icle TurnOff Animat ion for more informat ion)

      Animat ions can be turned back on by sett ing the property to false

      Example 1 Toggle animat ion on and of f

      Javascript

      var toggleFx = function() $fxoff = $fxofftoggleFx()

      $(button)cl ick(toggleFx)

      $(input)cl ick(function() $(div)toggle(slow))

      CSS

      div width50px height30px margin5px floatleft backgroundgreen

      HTML

      ltpgtltinput type=button value=Rungt ltbuttongtToggle fxltbuttongtltpgtltdivgtltdivgt

      clearQueue see Data

      dequeue see Data

      queue see Data

      queue see Data

      stop

      Stop the current ly-running animat ion on the matched elements

      Added in version 12

      stop(clearQueue jumpToEnd)jQuery

      clearQueueBoolean (opt ional) A Boolean indicat ing whether to remove queuedanimat ion as well Defaults to false

      jumpToEndBoolean (opt ional) A Boolean indicat ing whether to complete the currentanimat ion immediately Defaults to false

      When stop() is called on an element the current ly-running animat ion (if any) is immediatelystopped If for instance an element is being hidden with slideUp() when stop() is called theelement will now st ill be displayed but will be a f ract ion of its previous height Callback funct ions

      are not called

      If more than one animat ion method is called on the same element the later animat ions areplaced in the ef fects queue for the element These animat ions will not begin unt il the f irst onecompletes When stop() is called the next animat ion in the queue begins immediately If theclearQueue parameter is provided with a value of t rue then the rest of the animat ions in thequeue are removed and never run

      If the jumpToEnd property is provided with a value of t rue the current animat ion stops but theelement is immediately given its target values for each CSS property In our above slideUp()example the element would be immediately hidden The callback funct ion is then immediatelycalled if provided

      The usefulness of the stop() method is evident when we need to animate an element onmouseenter and mouseleave

      ltdiv id=hovermegt Hover me ltimg id=hoverme src=bookpng alt= width=100 height=123 gtltdivgt

      We can create a nice fade ef fect without the common problem of mult iple queued animat ionsby adding stop(true t rue) to the chain

      $(hoverme-stop-2)hover(function() $(this)find( img)stop(true true)fadeOut() function() $(this)find( img)stop(true true)fadeIn())

      Animations may be stopped globally by setting the property $fxoff to true Whenthis is done all animation methods will immediately set elements to their finalstate when called rather than displaying an effect

      Example 1 Click the Go button once to start the animat ion then click the STOP button to stopit where it s current ly posit ioned Another opt ion is to click several buttons to queue them upand see that stop just kills the current ly playing one

      Javascript

      Start animation $(go)cl ick(function()$(block)animate(left +=100px 2000))

      Stop animation when button is cl icked $(stop)cl ick(function()$(block)stop())

      Start animation in the opposite direction $(back)cl ick(function()$(block)animate(left -=100px 2000))

      HTML

      ltbutton id=gogtGoltbuttongt ltbutton id=stopgtSTOPltbuttongtltbutton id=backgtBackltbuttongtltdiv class=blockgtltdivgt

      CSS

      div position absolute background-color abcleft 0pxtop30pxwidth 60px height 60pxmargin 5px

      animate

      Perform a custom animat ion of a set of CSS propert ies

      Added in version 10

      animate(propert ies opt ions)jQuery

      propert iesMap A map of CSS propert ies that the animat ion will move toward

      opt ionsMap A map of addit ional opt ions to pass to the method Supported keys

      durat ion A string or number determining how long theanimat ion will run

      easing A string indicat ing which easing funct ion to use for thetransit ion

      complete A funct ion to call once the animat ion is completestep A funct ion to be called af ter each step of the animat ionqueue A Boolean indicat ing whether to place the animat ion in

      the ef fects queue If false the animat ion will begin immediatelyspecialEasing A map of one or more of the CSS propert ies

      def ined by the propert ies argument and their correspondingeasing funct ions (added 14)

      The animate() method allows us to create animat ion ef fects on any numeric CSS property Theonly required parameter is a map of CSS propert ies This map is similar to the one that can besent to the css() method except that the range of propert ies is more restrict ive

      Animation Properties and Values

      All animated propert ies should be animated to a single numeric value except as noted belowmost propert ies that are non-numeric cannot be animated using basic jQuery funct ionality (Forexample width height or lef t can be animated but background-color cannot be) Propertyvalues are t reated as a number of pixels unless otherwise specif ied The units em and can bespecif ied where applicable

      In addit ion to style propert ies some non-style propert ies such as scrollTop and scrollLef t aswell as custom propert ies can be animated

      Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

      In addit ion to numeric values each property can take the strings show hide and toggleThese shortcuts allow for custom hiding and showing animat ions that take into account thedisplay type of the element

      Animated propert ies can also be relat ive If a value is supplied with a leading += or -= sequenceof characters then the target value is computed by adding or subtract ing the given numberfrom the current value of the property

      Unlike shorthand animat ion methods such as slideDown() and fadeIn() the animate() methoddoes not make hidden elements visible as part of the ef fect For example given$(someElement )hide()animate(height20px 500) the animat ion will run but the element willremain hidden

      Duration

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      Complete Function

      If supplied the complete callback funct ion is f ired once the animat ion is complete This can beuseful for stringing dif ferent animat ions together in sequence The callback is not sent anyarguments but this is set to the DOM element being animated If mult iple elements areanimated the callback is executed once per matched element not once for the animat ion as awhole

      Basic Usage

      To animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 style=position relative left 10px gt

      To animate the opacity lef t of fset and height of the image simultaneously

      $(clickme)cl ick(function() $(book)animate( opacity 025 left +=50 height toggle 5000 function() Animation complete ))

      Note that the target value of the height property is toggle Since the image was visible beforethe animat ion shrinks the height to 0 to hide it A second click then reverses this t ransit ion

      The opacity of the image is already at its target value so this property is not animated by thesecond click Since the target value for lef t is a relat ive value the image moves even farther tothe right during this second animat ion

      Direct ional propert ies (top right bot tom lef t ) have no discernible ef fect on elements if theirposit ion style property is stat ic which it is by default

      Note The jQuery UI project extends the animate() method by allowing some non-numeric styles such as colors to be animated The project also includesmechanisms for specifying animations through CSS classes rather than individualattributes

      Note if attempting to animate an element with a height or width of 0px wherecontents of the element are visible due to overflow jQuery may clip this overflowduring animation By fixing the dimensions of the original element being hiddenhowever it is possible to ensure that the animation runs smoothly A clearfix canbe used to automatically fix the dimensions of your main element without the needto set this manually

      Step Function

      The second version of animate() provides a step opt ion acirceurordquo a callback funct ion that is f ired ateach step of the animat ion This funct ion is useful for enabling custom animat ion types oraltering the animat ion as it is occurring It accepts two arguments (now and fx) and this is setto the DOM element being animated

      now the numeric value of the property being animated at each step

      fx a reference to the jQueryfx prototype object which contains a number of propert iessuch as elem for the animated element start and end for the f irst and last value of theanimated property respect ively and prop for the property being animated

      Note that the step funct ion is called for each animated property on each animated element Forexample given two list items the step funct ion f ires four t imes at each step of the animat ion

      $( l i )animate( opacity 5 height 50 step function(now fx) var data = fxelemid + + fxprop + + now $(body)append(ltdivgt + data + ltdivgt) )

      Easing

      The remaining parameter of animate() is a string naming an easing funct ion to use An easingfunct ion specif ies the speed at which the animat ion progresses at dif ferent points within theanimat ion The only easing implementat ions in the jQuery library are the default called swingand one that progresses at a constant pace called linear More easing funct ions are availablewith the use of plug-ins most notably the jQuery UI suite

      Per-property Easing

      As of jQuery version 14 you can set per-property easing funct ions within a single animate()call In the f irst version of animate() each property can take an array as its value The f irstmember of the array is the CSS property and the second member is an easing funct ion If a per-property easing funct ion is not def ined for a part icular property it uses the value of theanimate() methods opt ional easing argument If the easing argument is not def ined thedefault swing funct ion is used

      For example to simultaneously animate the width and height with the swing easing funct ionand the opacity with the linear easing funct ion

      $(clickme)cl ick(function() $(book)animate( width [toggle swing] height [toggle swing] opacity toggle 5000 l inear function() $(this)after(ltdivgtAnimation completeltdivgt) ))

      In the second version of animate() the opt ions map can include the specialEasing propertywhich is itself a map of CSS propert ies and their corresponding easing funct ions For exampleto simultaneously animate the width using the linear easing funct ion and the height using the

      easeOutBounce easing funct ion

      $(clickme)cl ick(function() $(book)animate( width toggle height toggle duration 5000 specialEasing width l inear height easeOutBounce complete function() $(this)after(ltdivgtAnimation completeltdivgt) ))

      As previously noted a plugin is required for the easeOutBounce funct ion

      Example 1 Click the button to animate the div with a number of dif ferent propert ies

      Javascript

      Using multiple unit types within one animation

      $(go)cl ick(function() $(block)animate( width 70 opacity 04 marginLeft 06in fontSize 3em borderWidth 10px 1500 ))

      HTML

      ltbutton id=gogtampraquo Runltbuttongt

      ltdiv id=blockgtHelloltdivgt

      CSS

      div background-colorbcawidth100pxborder1px solid green

      Example 2 Animates a divs lef t property with a relat ive value Click several t imes on thebuttons to see the relat ive animat ions queued up

      Javascript

      $(right)cl ick(function() $(block)animate(left +=50px slow))

      $(left)cl ick(function() $(block)animate(left -=50px slow))

      HTML

      ltbutton id=leftgtamplaquoltbuttongt ltbutton id=rightgtampraquoltbuttongtltdiv class=blockgtltdivgt

      CSS

      div positionabsolute background-colorabc left50px width90px height90px margin5px

      Example 3 The f irst but ton shows how an unqueued animat ion works It expands the div out to90 width while the font-size is increasing Once the font-size change is complete the borderanimat ion will begin The second button starts a t radit ional chained animat ion where eachanimat ion will start once the previous animat ion on the element has completed

      Javascript

      $( go1 )cl ick(function() $( block1 )animate( width 90 queue false duration 3000 ) animate( fontSize 24px 1500 ) animate( borderRightWidth 15px 1500 ))

      $( go2 )cl ick(function() $( block2 )animate( width 90 1000 ) animate( fontSize 24px 1000 ) animate( borderLeftWidth 15px 1000 ))

      $( go3 )cl ick(function() $( go1 )add( go2 )cl ick())

      $( go4 )cl ick(function() $( div )css( width fontSize borderWidth ))

      HTML

      ltbutton id=go1gtampraquo Animate Block1ltbuttongtltbutton id=go2gtampraquo Animate Block2ltbuttongtltbutton id=go3gtampraquo Animate Bothltbuttongt

      ltbutton id=go4gtampraquo Resetltbuttongtltdiv id=block1gtBlock1ltdivgtltdiv id=block2gtBlock2ltdivgt

      CSS

      div background-colorbca width200px height11em text-aligncenter border2px solid green margin3px font-size14pxbutton font-size14px

      Example 4 Animates the f irst divs lef t property and synchronizes the remaining divs using thestep funct ion to set their lef t propert ies at each stage of the animat ion

      Javascript

      $( go )cl ick(function() $( blockfirst )animate( left 100 duration 1000 step function( now fx ) $( blockgt(0) )css( left now ) ))

      CSS

      div position relative background-color abc width 40px height 40px float left margin 5px

      HTML

      ltpgtltbutton id=gogtRun Acircraquoltbuttongtltpgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgt

      Example 5 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

      Javascript

      $( p )animate( height toggle opacity toggle slow )

      Example 6 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds

      Javascript

      $( p )animate( left 50 opacity 1 500 )

      Example 7 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion Note this code will donothing unless the paragraph element is hidden

      Javascript

      $( p )animate( opacity show slow easein )

      Example 8 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

      Javascript

      $( p )animate( height toggle opacity toggle duration slow )

      Example 9 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds It also will do it outside the queue meaning itwill automat ically start without wait ing for its turn

      Javascript

      $( p )animate( left 50px opacity 1 duration 500 queue false )

      Example 10 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion

      Javascript

      $( p )animate( opacity show duration slow easing easein )

      Example 11 An example of using a callback funct ion The f irst argument is an array of CSSpropert ies the second specif ies that the animat ion should take 1000 milliseconds to completethe third states the easing type and the fourth argument is an anonymous callback funct ion

      Javascript

      $( p )animate( height200 width400 opacity 5 1000 l inear function() alert(all done) )

      fadeTo

      Adjust the opacity of the matched elements

      Added in version 143

      fadeTo(durat ion opacity easing callback)jQuery

      durat ionStringNumber A string or number determining how long the animat ion will run

      opacityNumber A number between 0 and 1 denot ing the target opacity

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The fadeTo() method animates the opacity of the matched elements

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied the default durat ion of 400 milliseconds is usedUnlike the other ef fect methods fadeTo() requires that durat ion be explicit ly specif ied

      If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly shown we can dim it slowly $(clickme)cl ick(function() $(book)fadeTo(slow 05 function() Animation complete ) )

      With durat ion set to 0 this method just changes the opacity CSSproperty so fadeTo(0 opacity) is the same as css(opacity opacity)

      Example 1 Animates f irst paragraph to fade to an opacity of 033 (33about one third visible) complet ing the animat ion within 600milliseconds

      Javascript

      $(pfirst)cl ick(function () $(this)fadeTo(slow 033))

      HTML

      ltpgtClick this paragraph to see it fadeltpgt

      ltpgtCompare to this one that wont fadeltpgt

      Example 2 Fade div to a random opacity on each click complet ing theanimat ion within 200 milliseconds

      Javascript

      $(div)cl ick(function () $(this)fadeTo(fast Mathrandom()))

      CSS

      p width80px margin0 padding5px div width40px height40px positionabsolute divone top0 left0 backgroundf00 divtwo top20px left20px background0f0 divthree top40px left40px background00f

      HTML

      ltpgtAnd this is the l ibrary that John builtltpgt

      ltdiv id=onegtltdivgtltdiv id=twogtltdivgtltdiv id=threegtltdivgt

      Example 3 Find the right answer The fade will take 250 milliseconds andchange various styles when it completes

      Javascript

      var getPos = function (n) return (Mathfloor(n) 90) + px$(p)each(function (n) var r = Mathfloor(Mathrandom() 3)var tmp = $(this)text()$(this)text($(peq( + r + ))text())$(peq( + r + ))text(tmp)$(this)css(left getPos(n)))$(div)each(function (n) $(this)css(left getPos(n)) )css(cursor pointer)cl ick(function () $(this)fadeTo(250 025 function () $(this)css(cursor ) prev()css(font-weight bolder font-style ital ic) ) )

      CSS

      div p width80px height40px top0 margin0 positionabsolute padding-top8px p backgroundfcc text-aligncenter div backgroundblue

      HTML

      ltpgtWrongltpgtltdivgtltdivgtltpgtWrongltpgtltdivgtltdivgt

      ltpgtRightltpgtltdivgtltdivgt

      fadeOut

      Hide the matched elements by fading them to t ransparent

      Added in version 143

      fadeOut(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The fadeOut() method animates the opacity of the matched elements Once the opacityreaches 0 the display style property is set to none so the element no longer af fects the layoutof the page

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

      With the element init ially shown we can hide it slowly

      $(clickme)cl ick(function() $(book)fadeOut(slow function() Animation complete ))

      Note To avoid unnecessary DOM manipulation fadeOut() willnot hide an element that is already considered hidden Forinformation on which elements jQuery considers hidden seehidden Selector

      Easing

      As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

      As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

      Example 1 Animates all paragraphs to fade out complet ing theanimat ion within 600 milliseconds

      Javascript

      $(p)cl ick(function () $(p)fadeOut(slow) )

      CSS

      p font-size150 cursorpointer

      HTML

      ltpgt If you click on this paragraph youl l see it just fade away ltpgt

      Example 2 Fades out spans in one sect ion that you click on

      Javascript

      $(span)cl ick(function () $(this)fadeOut(1000 function () $(div)text( + $(this)text() + has faded) $(this)remove() ) ) $(span)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

      CSS

      span cursorpointer spanhil ite backgroundyellow div displayinline colorred

      HTML

      lth3gtFind the modifiers - ltdivgtltdivgtlth3gt ltpgt If you ltspangtreallyltspangt want to go outside ltspangtin the coldltspangt then make sure to wear your ltspangtwarmltspangt jacket given to you by your ltspangtfavoriteltspangt teacher ltpgt

      Example 3 Fades out two divs one with a linear easing and one with the default swingeasing

      Javascript

      $(btn1)cl ick(function() function complete() $(ltdivgt)text(thisid)appendTo(log) $(box1)fadeOut(1600 l inear complete) $(box2)fadeOut(1600 complete))

      $(btn2)cl ick(function() $(div)show() $(log)empty())

      CSS

      boxbutton floatleft margin5px 10px 5px 0 box height80px width80px background090 log clearleft

      HTML

      ltbutton id=btn1gtfade outltbuttongtltbutton id=btn2gtshowltbuttongt

      ltdiv id=loggtltdivgt

      ltdiv id=box1 class=boxgtlinearltdivgtltdiv id=box2 class=boxgtswingltdivgt

      fadeIn

      Display the matched elements by fading them to opaque

      Added in version 143

      fadeIn(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The fadeIn() method animates the opacity of the matched elements

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly hidden we can show it slowly $(clickme)cl ick(function() $(book)fadeIn(slow function() Animation complete ) )

      Easing

      As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

      As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

      Example 1 Animates hidden divs to fade in one by one complet ing eachanimat ion within 600 milliseconds

      Javascript

      $(documentbody)cl ick(function () $(divhiddenfirst)fadeIn(slow) )

      CSS

      span colorred cursorpointer div margin3px width80px displaynone height80px floatleft divone backgroundf00 divtwo background0f0 divthree background00f

      HTML

      ltspangtClick hereltspangt

      ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt

      Example 2 Fades a red block in over the text Once the animat ion is done it quickly fades inmore text on top

      Javascript

      $(a)cl ick(function () $(div)fadeIn(3000 function () $(span)fadeIn(100) ) return false )

      CSS

      p positionrelative width400px height90px div positionabsolute width400px height65px font-size36px text-aligncenter coloryellow backgroundred padding-top25px top0 left0 displaynone span displaynone

      HTML

      ltpgt 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 (lta href=gtclickltagt) ltdivgtltspangtCENSOREDltspangtltdivgt

      ltpgt

      slideToggle

      Display or hide the matched elements with a sliding mot ion

      Added in version 143

      slideToggle(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The slideToggle() method animates the height of the matched elements This causes lowerparts of the page to slide up or down appearing to reveal or conceal the items If the element isinit ially displayed it will be hidden if hidden it will be shown The display property is saved andrestored as needed If an element has a display value of inline then is hidden and shown it willonce again be displayed inline When the height reaches 0 af ter a hiding animat ion the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster ones

      The strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

      We will cause slideToggle() to be called when another element is clicked

      $(clickme)cl ick(function() $(book)sl ideToggle(slow function() Animation complete ))

      With the element init ially shown we can hide it slowly with the f irst click

      A second click will show the element once again

      Easing

      As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

      As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed their

      animat ions ( See the example for promise() )

      Example 1 Animates all paragraphs to slide up or down complet ing theanimat ion within 600 milliseconds

      Javascript

      $(button)cl ick(function () $(p)sl ideToggle(slow) )

      CSS

      p width400px

      HTML

      ltbuttongtToggleltbuttongt

      ltpgt This is the paragraph to end all paragraphs You should feel ltemgtluckyltemgt to have seen such a paragraph in your l i fe Congratulations ltpgt

      Example 2 Animates divs between dividers with a toggle that makessome appear and some disappear

      Javascript

      $(aa)cl ick(function () $(divnot(sti l l))sl ideToggle(slow function () var n = parseInt($(span)text() 10) $(span)text(n + 1) ) )

      CSS

      div backgroundb977d1 margin3px width60px height60px floatleft divsti l l background345 width5px divhider displaynone span colorred p clear left

      HTML

      ltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv style=displaynonegtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltpgtltbutton id=aagtToggleltbuttongt There have been ltspangt0ltspangt toggled divsltpgt

      slideUp

      Hide the matched elements with a sliding mot ion

      Added in version 143

      slideUp(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The slideUp() method animates the height of the matched elements This causes lower partsof the page to slide up appearing to conceal the items Once the height reaches 0 the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

      With the element init ially shown we can hide it slowly

      $(clickme)cl ick(function() $(book)sl ideUp(slow function() Animation complete ))

      Easing

      As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

      As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

      Example 1 Animates all divs to slide up complet ing the animat ion within400 milliseconds

      Javascript

      $(documentbody)cl ick(function () i f ($(divfirst)is(hidden)) $(div)show(slow) else $(div)sl ideUp() )

      CSS

      div background3d9a44 margin3px width80px height40px floatleft

      HTML

      Click me ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

      ltdivgtltdivgt

      Example 2 Animates the parent paragraph to slide up complet ing the animat ion within 200milliseconds Once the animat ion is done it displays an alert

      Javascript

      $(button)cl ick(function () $(this)parent()sl ideUp(slow function () $(msg)text($(button this)text() + has completed) ) )

      CSS

      div margin2px

      HTML

      ltdivgt ltbuttongtHide Oneltbuttongt ltinput type=text value=One gt

      ltdivgtltdivgt ltbuttongtHide Twoltbuttongt ltinput type=text value=Two gt

      ltdivgtltdivgt ltbuttongtHide Threeltbuttongt ltinput type=text value=Three gt

      ltdivgtltdiv id=msggtltdivgt

      slideDown

      Display the matched elements with a sliding mot ion

      Added in version 143

      slideDown(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      The slideDown() method animates the height of the matched elements This causes lowerparts of the page to slide down making way for the revealed items

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

      With the element init ially hidden we can show it slowly

      $(clickme)cl ick(function() $(book)sl ideDown(slow function() Animation complete ))

      Easing

      As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

      Callback Function

      If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

      As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

      Example 1 Animates all divs to slide down and show themselves over600 milliseconds

      Javascript

      $(documentbody)cl ick(function () if ($(divfirst)is(hidden)) $(div)sl ideDown(slow) else $(div)hide())

      CSS

      div backgroundde9a44 margin3px width80px height40px displaynone floatleft

      HTML

      Click meltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

      Example 2 Animates all inputs to slide down complet ing the animat ion within 1000milliseconds Once the animat ion is done the input look is changed especially if it is the middleinput which gets the focus

      Javascript

      $(div)cl ick(function () $(this)css( borderStyleinset cursorwait )$(input)sl ideDown(1000function()$(this)css(border 2px red inset)fi lter(middle) css(background yellow) focus()$(div)css(visibil ity hidden)))

      CSS

      div backgroundcfd margin3px width50px text-aligncenter floatleft cursorpointerborder2px outset black font-weightbolder input displaynone width120px floatleft margin10px

      HTML

      ltdivgtPushltdivgtltinput type=text gtltinput type=text class=middle gt

      ltinput type=text gt

      toggle

      Display or hide the matched elements

      Added in version 13

      toggle(showOrHide)jQuery

      showOrHideBoolean A Boolean indicat ing whether to show or hide the elements

      With no parameters the toggle() method simply toggles the visibility of elements

      $(target)toggle()

      The matched elements will be revealed or hidden immediately with no animat ion by changingthe CSS display property If the element is init ially displayed it will be hidden if hidden it will beshown The display property is saved and restored as needed If an element has a display valueof inline then is hidden and shown it will once again be displayed inline

      When a durat ion is provided toggle() becomes an animat ion method The toggle() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 af ter a hiding animat ion the display style property is set to none to ensurethat the element no longer af fects the layout of the page

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      Note The event handling suite also has a method named toggle() Which one isfired depends on the set of arguments passed

      As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use of

      plug-ins most notably the jQuery UI suite

      If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

      We will cause toggle() to be called when another element is clicked

      $(clickme)cl ick(function() $(book)toggle(slow function() Animation complete ))

      With the element init ially shown we can hide it slowly with the f irst click

      A second click will show the element once again

      The second version of the method accepts a Boolean parameter If thisparameter is t rue then the matched elements are shown if false theelements are hidden In essence the statement

      $(foo)toggle(showOrHide)

      is equivalent to

      i f ( showOrHide == true ) $(foo)show() else if ( showOrHide == false ) $(foo)hide()

      Example 1 Toggles all paragraphs

      Javascript

      $(button)cl ick(function () $(p)toggle())

      HTML

      ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

      Example 2 Animates all paragraphs to be shown if they are hidden andhidden if they are visible complet ing the animat ion within 600milliseconds

      Javascript

      $(button)cl ick(function () $(p)toggle(slow))

      CSS

      p backgrounddadfont-weightboldfont-size16px

      HTML

      ltbuttongtToggle emltbuttongt

      ltpgtHiyaltpgtltpgtSuch interesting text ehltpgt

      Example 3 Shows all paragraphs then hides them all back and forth

      Javascript

      var fl ip = 0$(button)cl ick(function () $(p)toggle( fl ip++ 2 == 0 ))

      HTML

      ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

      hide

      Hide the matched elements

      Added in version 143

      hide(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determininghow long the animat ion will run

      easingString (opt ional) A string indicat ing whicheasing funct ion to use for the t ransit ion

      callbackCallback (opt ional) A funct ion to call once theanimat ion is complete

      With no parameters the hide() method is the simplest way to hide an element

      $(target)hide()

      The matched elements will be hidden immediately with no animat ion This is roughly equivalentto calling css(display none) except that the value of the display property is saved in jQuerysdata cache so that display can later be restored to its init ial value If an element has a displayvalue of inline then is hidden and shown it will once again be displayed inline

      When a durat ion is provided hide() becomes an animat ion method The hide() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 the display style property is set to none to ensure that the element nolonger af fects the layout of the page

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

      If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly shown we can hide it slowly$(clickme)cl ick(function() $(book)hide(slow function() alert(Animation complete) ))

      Example 1 Hides all paragraphs then the link on click

      Javascript

      $(p)hide() $(a)cl ick(function ( event ) eventpreventDefault() $(this)hide() )

      HTML

      ltpgtHelloltpgt lta href=gtClick to hide me tooltagt ltpgtHere is another paragraphltpgt

      Example 2 Animates all shown paragraphs to hide slowly complet ingthe animat ion within 600 milliseconds

      Javascript

      $(button)cl ick(function () $(p)hide(slow) )

      CSS

      p backgrounddad font-weightbold

      HTML

      ltbuttongtHide emltbuttongt

      ltpgtHiyaltpgt ltpgtSuch interesting text ehltpgt

      Example 3 Animates all spans (words in this case) to hide fast ly complet ing each animat ionwithin 200 milliseconds Once each animat ion is done it starts the next one

      Javascript

      $(hidr)cl ick(function () $(spanlast-child)hide(fast function () use callee so dont have to name the function $(this)prev()hide(fast argumentscallee) ) ) $(showr)cl ick(function () $(span)show(2000) )

      CSS

      span backgrounddef3ca padding3px floatleft

      HTML

      ltbutton id=hidrgtHideltbuttongt ltbutton id=showrgtShowltbuttongt ltdivgt

      ltspangtOnceltspangt ltspangtuponltspangt ltspangtaltspangt ltspangttimeltspangt ltspangtthereltspangt ltspangtwereltspangt ltspangtthreeltspangt ltspangtprogrammersltspangt

      ltdivgt

      Example 4 Hides the divs when clicked over 2 seconds then removes the div element when itshidden Try clicking on more than one box at a t ime

      Javascript

      for (var i = 0 i lt 5 i++) $(ltdivgt)appendTo(documentbody) $(div)cl ick(function () $(this)hide(2000 function () $(this)remove() ) )

      CSS

      div backgroundece023 width30px height40px margin2px floatleft

      HTML

      ltdivgtltdivgt

      show

      Display the matched elements

      Added in version 143

      show(durat ion easing callback)jQuery

      durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

      easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

      callbackCallback (opt ional) A funct ion to call once the animat ion is complete

      With no parameters the show() method is the simplest way to display an element

      $(target)show()

      The matched elements will be revealed immediately with no animat ion This is roughlyequivalent to calling css(display block) except that the display property is restored towhatever it was init ially If an element has a display value of inline then is hidden and shown itwill once again be displayed inline

      Note If using important in your styles such as display none important it is necessary tooverride the style using css(display block important ) should you wish for show() to funct ioncorrect ly

      When a durat ion is provided show() becomes an animat ion method The show() methodanimates the width height and opacity of the matched elements simultaneously

      Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

      As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

      If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

      We can animate any element such as a simple image

      ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly hidden we can show it slowly$(clickme)cl ick(function() $(book)show(slow function() Animation complete ))

      Example 1 Animates all hidden paragraphs to show slowly complet ingthe animat ion within 600 milliseconds

      Javascript

      $(button)cl ick(function () $(p)show(slow) )

      CSS

      p backgroundyellow

      HTML

      ltbuttongtShow itltbuttongt

      ltp style=display nonegtHello 2ltpgt

      Example 2 Animates all hidden divs to show fast ly in order complet ingeach animat ion within 200 milliseconds Once each animat ion is done itstarts the next one

      Javascript

      $(showr)cl ick(function () $(diveq(0))show(fast function () use callee so dont have to name the function $(this)next(div)show(fast argumentscallee) ))$(hidr)cl ick(function () $(div)hide(2000))

      CSS

      div backgrounddef3ca margin3px width80px displaynone floatleft text-aligncenter

      HTML

      ltbutton id=showrgtShowltbuttongt ltbutton id=hidrgtHideltbuttongt ltdivgtHello 3ltdivgt

      ltdivgthowltdivgt ltdivgtareltdivgt ltdivgtyoultdivgt

      Example 3 Shows all span and input elements with an animat ion Once the animat ion is done itchanges the text

      Javascript

      function doIt() $(spandiv)show(slow) can pass in function name $(button)cl ick(doIt)

      $(form)submit(function () if ($(input)val() == yes) $(p)show(4000 function () $(this)text(Ok DONE (now showing)) ) $(spandiv)hide(fast) to stop the submit return false )

      CSS

      span displaynone div displaynone p font-weightbold background-colorfcd

      HTML

      ltbuttongtDo itltbuttongt ltspangtAre you sure (type yes if you are) ltspangt ltdivgt ltformgt ltinput type=text value=asldkfjalsdfgt ltformgt ltdivgt ltp style=displaynonegtIm hiddenltpgt

      Ajax

      jQueryajaxPrefilter

      Handle custom Ajax opt ions or modify exist ing opt ions before each request is sent and beforethey are processed by $ajax()

      Added in version 15

      jQueryajaxPref ilter(dataTypes handler(opt ions originalOpt ions jqXHR))undef ined

      dataTypesString (opt ional) An opt ional string containing one or more

      space-separated dataTypes

      handler(opt ionsoriginalOpt ionsjqXHR)Funct ion

      A handler to set default values for future Ajaxrequests

      A typical pref ilter registrat ion using $ajaxPref ilter() looks like this

      $ajaxPrefi lter( function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

      where

      opt ions are the request opt ions

      originalOpt ions are the opt ions as provided to the ajax method unmodif ied and thuswithout defaults f rom ajaxSett ings

      jqXHR is the jqXHR object of the request

      Pref ilters are a perfect f it when custom opt ions need to be handled Given the following codefor example a call to $ajax() would automat ically abort a request to the same URL if thecustom abortOnRetry opt ion is set to t rue

      var currentRequests =

      $ajaxPrefi lter(function( options originalOptions jqXHR ) if ( optionsabortOnRetry ) i f ( currentRequests[ optionsurl ] ) currentRequests[ optionsurl ]abort() currentRequests[ optionsurl ] = jqXHR )

      Pref ilters can also be used to modify exist ing opt ions For example the following proxies cross-domain requests through ht tpmydomainnetproxy

      $ajaxPrefi lter( function( options ) if ( optionscrossDomain ) optionsurl = httpmydomainnetproxy + encodeURIComponent( optionsurl ) optionscrossDomain = false )

      If the opt ional dataTypes argument is supplied the pref ilter will be only be applied to requestswith the indicated dataTypes For example the following only applies the given pref ilter toJSON and script requests

      $ajaxPrefi lter( json script function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

      The $ajaxPref ilter() method can also redirect a request to another dataType by returning thatdataType For example the following sets a request as script if the URL has some specif icpropert ies def ined in a custom isActuallyScript() funct ion

      $ajaxPrefi lter(function( options ) if ( isActuallyScript( optionsurl ) ) return script )

      This would ensure not only that the request is considered script but also that all the pref iltersspecif ically at tached to the script dataType would be applied to it

      ajaxComplete

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

      Added in version 10

      ajaxComplete(handler(event XMLHttpRequest ajaxOpt ions))jQuery

      handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

      Whenever an Ajax request completes jQuery t riggers the ajaxComplete event Any and allhandlers that have been registered with the ajaxComplete() method are executed at this t ime

      To observe this method in act ion we can set up a basic Ajax load request

      ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

      When the user clicks the button and the Ajax request completes the log message is displayed

      Note Because ajaxComplete() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

      All ajaxComplete handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxComplete handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

      Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

      $(log)ajaxComplete(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxComplete handler The result is + xhrresponseHTML) )

      Example 1 Show a message when an Ajax request completes

      Javascript

      $(msg)ajaxComplete(function(eventrequest settings) $(this)append(ltligtRequest Completeltl igt) )

      serializeArray see Forms

      serialize see Forms

      jQueryajaxSetup

      Set default values for future Ajax requests

      Added in version 11

      jQueryajaxSetup(opt ions)

      opt ionsOpt ions A set of keyvalue pairs that conf igure the default Ajax request Allopt ions are opt ional

      For details on the sett ings available for $ajaxSetup() see $ajax()

      All subsequent Ajax calls using any funct ion will use the new sett ings unless overridden by theindividual calls unt il the next invocat ion of $ajaxSetup()

      For example the following sets a default for the url parameter before pinging the serverrepeatedly

      $ajaxSetup( url pingphp)

      Now each t ime an Ajax request is made the pingphp URL will be used automat ically

      $ajax( url not set here uses pingphp data name Dan)

      Note Global callback functions should be set with their respective global Ajaxevent handler methodsacirceurordquoajaxStart() ajaxStop() ajaxComplete() ajaxError()ajaxSuccess() ajaxSend()acirceurordquorather than within the options object for$ajaxSetup()

      Example 1 Sets the defaults for Ajax requests to the url xmlht tp disables global handlersand uses POST instead of GET The following Ajax requests then sends some data withouthaving to set anything else

      Javascript

      $ajaxSetup( url xmlhttp global false type POST

      ) $ajax( data myData )

      ajaxSuccess

      Attach a funct ion to be executed whenever an Ajax request completes successfully This is anAjax Event

      Added in version 10

      ajaxSuccess(handler(event XMLHttpRequest ajaxOpt ions))jQuery

      handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

      Whenever an Ajax request completes successfully jQuery t riggers the ajaxSuccess event Anyand all handlers that have been registered with the ajaxSuccess() method are executed at thist ime

      To observe this method in act ion we can set up a basic Ajax load request

      ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

      When the user clicks the button and the Ajax request completes successfully the log messageis displayed

      Note Because ajaxSuccess() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

      All ajaxSuccess handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxSuccess handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

      Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

      $(log)ajaxSuccess(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSuccess handler The ajax response was + xhrresponseHTML ) )

      Example 1 Show a message when an Ajax request completes successfully

      Javascript

      $(msg)ajaxSuccess(function(evt request settings) $(this)append(ltligtSuccessful Requestltl igt) )

      ajaxStop

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

      Added in version 10

      ajaxStop(handler())jQuery

      handler()Funct ion The funct ion to be invoked

      Whenever an Ajax request completes jQuery checks whether there are any other outstandingAjax requests If none remain jQuery t riggers the ajaxStop event Any and all handlers that havebeen registered with the ajaxStop() method are executed at this t ime The ajaxStop event isalso t riggered if the last outstanding Ajax request is cancelled by returning false within thebeforeSend callback funct ion

      To observe this method in act ion we can set up a basic Ajax load request

      ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

      When the user clicks the button and the Ajax request completes the log message is displayed

      Because ajaxStop() is implemented as a method of jQuery object instances we can use thethis keyword as we do here to refer to the selected elements within the callback funct ion

      Example 1 Hide a loading message af ter all the Ajax requests have stopped

      Javascript

      $(loading)ajaxStop(function() $(this)hide() )

      ajaxStart

      Register a handler to be called when the f irst Ajax request begins This is an Ajax Event

      Added in version 10

      ajaxStart(handler())jQuery

      handler()Funct ion The funct ion to be invoked

      Whenever an Ajax request is about to be sent jQuery checks whether there are any otheroutstanding Ajax requests If none are in progress jQuery t riggers the ajaxStart event Any andall handlers that have been registered with the ajaxStart() method are executed at this t ime

      To observe this method in act ion we can set up a basic Ajax load request

      ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

      When the user clicks the button and the Ajax request is sent the log message is displayed

      Note Because ajaxStart() is implemented as a method of jQuery object instances we can usethe this keyword as we do here to refer to the selected elements within the callback funct ion

      Example 1 Show a loading message whenever an Ajax request starts (and none is alreadyact ive)

      Javascript

      $(loading)ajaxStart(function() $(this)show() )

      ajaxSend

      Attach a funct ion to be executed before an Ajax request is sent This is an Ajax Event

      Added in version 10

      ajaxSend(handler(event jqXHR ajaxOpt ions))jQuery

      handler(event jqXHR ajaxOpt ions)Funct ion The funct ion to be invoked

      Whenever an Ajax request is about to be sent jQuery t riggers the ajaxSend event Any and allhandlers that have been registered with the ajaxSend() method are executed at this t ime

      To observe this method in act ion we can set up a basic Ajax load request

      ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

      When the user clicks the button and the Ajax request is about to begin the log message isdisplayed

      Note Because ajaxSend() is implemented as a method of jQuery instances we can use the thiskeyword as we do here to refer to the selected elements within the callback funct ion

      All ajaxSend handlers are invoked regardless of what Ajax request is to be sent If we mustdif ferent iate between the requests we can use the parameters passed to the handler Eacht ime an ajaxSend handler is executed it is passed the event object the jqXHR object (in version14 XMLHttpRequestobject) and the sett ings object that was used in the creat ion of the Ajaxrequest For example we can restrict our callback to only handling events dealing with apart icular URL

      $(log)ajaxSend(function(e jqxhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSend handler) )

      Example 1 Show a message before an Ajax request is sent

      Javascript

      $(msg)ajaxSend(function(evt request settings) $(this)append(ltligtStarting request at + settingsurl + ltl igt) )

      ajaxError

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

      Added in version 10

      ajaxError(handler(event jqXHR ajaxSett ings thrownError))jQuery

      handler(event jqXHR ajaxSett ings thrownError)Funct ion The funct ion to be invoked

      Whenever an Ajax request completes with an error jQuery t riggers the ajaxError event Any andall handlers that have been registered with the ajaxError() method are executed at this t ime

      To observe this method in act ion set up a basic Ajax load request

      ltbutton class=triggergtTriggerltbuttongtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

      Attach the event handler to any element

      $(divlog)ajaxError(function() $(this)text( Triggered ajaxError handler ))

      Now make an Ajax request using any jQuery method

      $(buttontrigger)cl ick(function() $(divresult)load( ajaxmissinghtml ))

      When the user clicks the button and the Ajax request fails because the requested f ile ismissing the log message is displayed

      Note Because ajaxError() is implemented as a method of jQuery object instances you can usethe this keyword within the callback funct ion to refer to the selected elements

      All ajaxError handlers are invoked regardless of what Ajax request was completed Todif ferent iate between the requests you can use the parameters passed to the handler Eacht ime an ajaxError handler is executed it is passed the event object the jqXHR object (prior tojQuery 15 the XHR object) and the sett ings object that was used in the creat ion of the

      request If the request failed because JavaScript raised an except ion the except ion object ispassed to the handler as a fourth parameter For example to restrict the error callback to onlyhandling events dealing with a part icular URL

      $( divlog )ajaxError(function(e jqxhr settings exception) if ( settingsurl == ajaxmissinghtml ) $(this)text( Triggered ajaxError handler ) )

      Example 1 Show a message when an Ajax request fails

      Javascript

      $(msg)ajaxError(function(event request settings) $(this)append(ltligtError requesting page + settingsurl + ltl igt))

      jQuerypost

      Load data f rom the server using a HTTP POST request

      Added in version 10

      jQuerypost(url data success(data textStatus jqXHR) dataType)jqXHR

      urlString A string containing the URL to which the request is sent

      dataMap String (opt ional) A map or string that is sent to the server with therequest

      success(datatextStatusjqXHR)Funct ion

      (opt ional) A callback funct ion that is executed if the requestsucceeds

      dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

      This is a shorthand Ajax funct ion which is equivalent to

      $ajax( type POST url url data data success success dataType dataType)

      The success callback funct ion is passed the returned data which will be an XML root elementor a text string depending on the MIME type of the response It is also passed the text statusof the response

      As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object)

      Most implementat ions will specify a success handler

      $post(ajaxtesthtml function(data) $( result)html(data))

      This example fetches the requested HTML snippet and inserts it on the page

      Pages fetched with POST are never cached so the cache and ifModif ied opt ions injQueryajaxSetup() have no ef fect on these requests

      The jqXHR Object

      As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $post() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

      The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $post() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

      Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $post(examplephp 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 jqxhrcomplete(function() alert(second complete) )

      Example 1 Request the test php page but ignore the return results

      Javascript

      $post(testphp)

      Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

      Javascript

      $post(testphp name John time 2pm )

      Example 3 pass arrays of data to the server (while st ill ignoring the return results)

      Javascript

      $post(testphp choices[] [ Jon Susan] )

      Example 4 send form data using ajax requests

      Javascript

      $post(testphp $(testform)serial ize())

      Example 5 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

      Javascript

      $post(testphp function(data) alert(Data Loaded + data) )

      Example 6 Alert out the results f rom request ing test php with an addit ional payload of data(HTML or XML depending on what was returned)

      Javascript

      $post(testphp name John time 2pm function(data) alert(Data Loaded + data) )

      Example 7 Gets the test php page content store it in a XMLHttpResponse object and appliesthe process() JavaScript funct ion

      Javascript

      $post(testphp name John time 2pm function(data) process(data) xml)

      Example 8 Posts to the test php page and gets contents which has been returned in jsonformat (Johnt ime=gt2pm)) gt)

      Javascript

      $post(testphp func getNameAndTime function(data) consolelog(dataname) John consolelog(datatime) 2pm json)

      Example 9 Post a form using ajax and put results in a div

      Javascript

      attach a submit handler to the form $(searchForm)submit(function(event)

      stop form from submitting normally eventpreventDefault() get some values from elements on the page var $form = $( this ) term = $formfind( input[name=s] )val() url = $formattr( 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 )empty()append( content ) ) )

      HTML

      ltform action= id=searchFormgt ltinput type=text name=s placeholder=Search gt ltinput type=submit value=Search gt ltformgt lt-- the result of the search wil l be rendered inside this div --gt ltdiv id=resultgtltdivgt

      jQuerygetScript

      Load a JavaScript f ile f rom the server using a GET HTTP request then execute it

      Added in version 10

      jQuerygetScript(url success(data textStatus))jqXHR

      urlString A string containing the URL to which the request is sent

      success(datatextStatus)Funct ion

      (opt ional) A callback funct ion that is executed if therequest succeeds

      This is a shorthand Ajax funct ion which is equivalent to

      $ajax( url url dataType script success success)

      The callback is passed the returned JavaScript f ile This is generally not useful as the script willalready have run at this point

      The script is executed in the global context so it can refer to other variables and use jQueryfunct ions Included scripts can have some impact on the current page

      $(result)html(ltpgtLorem ipsum dolor sit ametltpgt)

      Scripts are included and run by referencing the f ile name

      $getScript(ajaxtestjs function(data textStatus) consolelog(data) data returned consolelog(textStatus) success consolelog(Load was performed))

      Note Should you require an addit ional callback for errors when using the getScript() methodthe global ajaxError() callback event may be used to achieve this as follows

      $( divlog )ajaxError(function(e jqxhr settings exception) if (settingsdataType==script) $(this)text( Triggered ajaxError handler ) )

      Example 1 Load the of f icial jQuery Color Animat ion plugin dynamically and bind some coloranimat ions to occur once the new funct ionality is loaded

      Javascript

      $getScript(httpdevjquerycomviewtrunkpluginscolorjquerycolorjs function() $(go)cl ick(function() $(block)animate( backgroundColor pink 1000) delay(500) animate( backgroundColor blue 1000) ))

      HTML

      ltbutton id=gogtampraquo Runltbuttongt

      ltdiv class=blockgtltdivgt

      CSS

      block background-color blue width 150px height 70px margin 10px

      jQuerygetJSON

      Load JSON-encoded data f rom the server using a GET HTTP request

      Added in version 10

      jQuerygetJSON(url data success(data textStatus jqXHR))jqXHR

      urlString A string containing the URL to which the request issent

      dataMap (opt ional) A map or string that is sent to the serverwith the request

      success(data textStatusjqXHR)Funct ion

      (opt ional) A callback funct ion that is executed if therequest succeeds

      This is a shorthand Ajax funct ion which is equivalent to

      $ajax( url url dataType json data data success callback)

      Data that is sent to the server is appended to the URL as a query string If the value of the dataparameter is an object (map) it is converted to a string and url-encoded before it is appendedto the URL

      Most implementat ions will specify a success handler

      $getJSON(ajaxtestjson function(data) var items = []

      $each(data function(key val) itemspush(ltli id= + key + gt + val + ltl igt) )

      $(ltulgt class my-new-list html itemsjoin( ) )appendTo(body))

      This example of course relies on the structure of the JSON f ile

      one Singular sensation two Beady l ittle 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 success callback is passed the returned data which is typically a JavaScript object or arrayas def ined by the JSON structure and parsed using the $parseJSON() method It is also passedthe text status of the response

      As of jQuery 15 the success callback funct ion receives a jqXHR object (in jQuery 14 itreceived the XMLHttpRequest object) However since JSONP and cross-domain GET requestsdo not use XHR in those cases the jqXHR and textStatus parameters passed to the successcallback are undef ined

      Important As of jQuery 14 if the JSON file contains a syntax error the requestwill usually fail silently Avoid frequent hand-editing of JSON data for this reasonJSON is a data-interchange format with syntax rules that are stricter than those ofJavaScripts object literal notation For example all strings represented in JSONwhether they are properties or values must be enclosed in double-quotes Fordetails on the JSON format see httpjsonorg

      JSONP

      If the URL includes the string callback= (or similar as def ined by the server-side API) therequest is t reated as JSONP instead See the discussion of the jsonp data type in $ajax() for

      more details

      The jqXHR Object

      As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $getJSON() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

      The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $getJSON()to chain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

      Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $getJSON(examplejson 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 abovejqxhrcomplete(function() alert(second complete) )

      Example 1 Loads the four most recent cat pictures f rom the Flickr JSONP API

      Javascript

      $getJSON(httpapifl ickrcomservicesfeedsphotos_publicgnejsoncallback= tags cat tagmode any format json function(data) $each(dataitems function(iitem) $(ltimggt)attr(src itemmediam)appendTo(images) i f ( i == 3 ) return false ) )

      HTML

      ltdiv id=imagesgt

      ltdivgt

      CSS

      img height 100px float left

      Example 2 Load the JSON data f rom test js and access a name from the returned JSON data

      Javascript

      $getJSON(testjs function(json) alert(JSON Data + jsonusers[3]name) )

      Example 3 Load the JSON data f rom test js passing along addit ional data and access a namefrom the returned JSON data

      Javascript

      $getJSON(testjs name John time 2pm function(json) alert(JSON Data + jsonusers[3]name) )

      jQueryget

      Load data f rom the server using a HTTP GET request

      Added in version 10

      jQueryget(url data success(data textStatus jqXHR) dataType)jqXHR

      urlString A string containing the URL to which the request is sent

      dataMap String (opt ional) A map or string that is sent to the server with therequest

      success(datatextStatusjqXHR)Funct ion

      (opt ional) A callback funct ion that is executed if the requestsucceeds

      dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

      This is a shorthand Ajax funct ion which is equivalent to

      $ajax( url url data data success success dataType dataType)

      The success callback funct ion is passed the returned data which will be an XML root elementtext string JavaScript f ile or JSON object depending on the MIME type of the response It isalso passed the text status of the response

      As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object) However since JSONP and cross-domain GETrequests do not use XHR in those cases the (j)XHR and textStatus parameters passed to thesuccess callback are undef ined

      Most implementat ions will specify a success handler

      $get(ajaxtesthtml 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

      As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $get() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

      The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $get() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

      Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $get(examplephp 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 jqxhrcomplete(function() alert(second complete) )

      Example 1 Request the test php page but ignore the return results

      Javascript

      $get(testphp)

      Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

      Javascript

      $get(testphp name John time 2pm )

      Example 3 pass arrays of data to the server (while st ill ignoring the return results)

      Javascript

      $get(testphp choices[] [ Jon Susan] )

      Example 4 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

      Javascript

      $get(testphp function(data)alert(Data Loaded + data))

      Example 5 Alert out the results f rom request ing test cgi with an addit ional payload of data

      (HTML or XML depending on what was returned)

      Javascript

      $get(testcgi name John time 2pm function(data) alert(Data Loaded + data) )

      Example 6 Gets the test php page contents which has been returned in json format(Johnt ime=gt2pm)) gt) and adds it to the page

      Javascript

      $get(testphp function(data) $(body)append( Name + dataname ) John append( Time + datatime ) 2pm json)

      load

      Load data f rom the server and place the returned HTML into the matched element

      Added in version 10

      load(url data complete(responseText textStatus XMLHttpRequest))jQuery

      urlString A string containing the URL to which therequest is sent

      dataMap String A map or string that is sent to the server withthe request

      complete(responseText textStatusXMLHttpRequest)Funct ion

      (opt ional) A callback funct ion that is executedwhen the request completes

      This method is the simplest way to fetch data f rom the server It is roughly equivalent to$get(url data success) except that it is a method rather than global funct ion and it has animplicit callback funct ion When a successful response is detected (ie when textStatus issuccess or notmodif ied) load() sets the HTML contents of the matched element to thereturned data This means that most uses of the method can be quite simple

      $(result)load(ajaxtesthtml)

      The provided callback if any is executed af ter this post-processing has been performed

      $(result)load(ajaxtesthtml function() alert(Load was performed))

      In the two examples above if the current document does not contain an element with an ID ofresult the load() method is not executed

      The POST method is used if data is provided as an object otherwise GET is assumed

      Note The event handling suite also has a method named load() Which one isfired depends on the set of arguments passed

      Loading Page Fragments

      The load() method unlike $get() allows us to specify a port ion of the remote document to beinserted This is achieved with a special syntax for the url parameter If one or more spacecharacters are included in the string the port ion of the string following the f irst space isassumed 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(ajaxtesthtml container)

      When this method executes it retrieves the content of ajaxtest html but then jQuery parsesthe returned document to f ind the element with an ID of container This element along with itscontents is inserted into the element with an ID of result and the rest of the retrieveddocument is discarded

      jQuery uses the browsers innerHTML property to parse the retrieved document and insert itinto the current document During this process browsers of ten f ilter elements f rom thedocument such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements retrieved byload() may not be exact ly the same as if the document were retrieved direct ly by the browser

      Example 1 Load the main pages footer navigat ion into an ordered list

      Javascript

      $(new-nav)load( jq-footerNavigation l i)

      CSS

      body font-size 12px font-family Arial

      HTML

      ltbgtFooter navigationltbgtltol id=new-navgtltolgt

      Example 2 Display a not ice if the Ajax request encounters an error

      Javascript

      $(success)load(not-herephp function(response status xhr) if (status == error) var msg = Sorry but there was an error $(error)html(msg + xhrstatus + + xhrstatusText) )

      CSS

      body font-size 12px font-family Arial

      HTML

      ltbgtSuccessful Response (should be blank)ltbgtltdiv id=successgtltdivgtltbgtError Responseltbgtltdiv id=errorgtltdivgt

      Example 3 Load the feedshtml f ile into the div with the ID of feeds

      Javascript

      $(feeds)load(feedshtml)

      Results

      ltdiv id=feedsgtltbgt45ltbgt feeds foundltdivgt

      Example 4 pass arrays of data to the server

      Javascript

      $(objectID)load(testphp choices[] [ Jon Susan] )

      Example 5 Same as above but will POST the addit ional parameters to the server and acallback that is executed when the server is f inished responding

      Javascript

      $(feeds)load(feedsphp limit 25 function()alert(The last 25 entries in the feed have been loaded))

      jQueryajax

      Perform an asynchronous HTTP (Ajax) request

      Added in version 10

      jQueryajax(sett ings)jqXHR

      sett ingsMap A set of keyvalue pairs that conf igure the Ajax request All set t ings areopt ional A default can be set for any opt ion with $ajaxSetup()

      The $ajax() funct ion underlies all Ajax requests sent by jQuery It is of ten unnecessary todirect ly call this funct ion as several higher-level alternat ives like $get() and load() are availableand are easier to use If less common opt ions are required though $ajax() can be used moref lexibly

      At its simplest the $ajax() funct ion can be called with no arguments

      $ajax()

      Note Default set t ings can be set globally by using the $ajaxSetup() funct ion

      This example using no opt ions loads the contents of the current page but does nothing withthe result To use the result we can implement one of the callback funct ions

      The jqXHR Object

      The jQuery XMLHttpRequest (jqXHR) object returned by $ajax() as of jQuery 15 is a supersetof the browsers nat ive XMLHttpRequest object For example it contains responseText andresponseXML propert ies as well as a getResponseHeader() method When the transport

      mechanism is something other than XMLHttpRequest (for example a script tag for a JSONPrequest) the jqXHR object simulates nat ive XHR funct ionality where possible

      As of jQuery 151 the jqXHR object also contains the overrideMimeType() method (it wasavailable in jQuery 14x as well but was temporarily removed in jQuery 15) TheoverrideMimeType() method may be used in the beforeSend() callback funct ion for exampleto modify the response content-type header

      $ajax( url httpfiddlejshellnetfaviconpng beforeSend function( xhr ) xhroverrideMimeType( textplain charset=x-user-defined ) success function( data ) i f (console ampamp consolelog) consolelog( Sample of data datasl ice(0100) ) )

      The jqXHR objects returned by $ajax() as of jQuery 15 implement the Promise interface givingthem all the propert ies methods and behavior of a Promise (see Deferred object for moreinformat ion) For convenience and consistency with the callback names used by $ajax() jqXHRalso provides error() success() and complete() methods These methods take a funct ionargument that is called when the $ajax() request terminates and the funct ion receives thesame arguments as the correspondingly-named $ajax() callback This allows you to assignmult iple callbacks on a single request and even to assign callbacks af ter the request may havecompleted (If the request is already complete the callback is f ired immediately)

      Deprecation Notice The jqXHRsuccess() jqXHRerror() and jqXHRcomplete()callbacks will be deprecated in jQuery 18 To prepare your code for their eventualremoval use jqXHRdone() jqXHRfail() and jqXHRalways() instead

      Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $ajax( examplephp ) success(function() alert(success) ) error(function() alert(error) ) complete(function() alert(complete) )

      perform other work here

      Set another completion function for the request abovejqxhrcomplete(function() alert(second complete) )

      For backward compat ibility with XMLHttpRequest a jqXHR object will expose the followingpropert ies and methods

      readyState

      status

      statusText

      responseXML andor responseText when the underlying request responded with xmlandor text respect ively

      setRequestHeader(name value) which departs f rom the standard by replacing the oldvalue with the new one rather than concatenat ing the new value to the old one

      getAllResponseHeaders()

      getResponseHeader()

      abort()

      No onreadystatechange mechanism is provided however since success error complete andstatusCode cover all conceivable requirements

      Callback Function Queues

      The beforeSend error dataFilter success and complete opt ions all accept callback funct ionsthat are invoked at the appropriate t imes

      As of jQuery 15 the error (fail) success (done) and complete (always as of jQuery 16)callback hooks are f irst-in f irst-out managed queues This means you can assign more thanone callback for each hook See Deferred object methods which are implemented internally forthese $ajax() callback hooks

      The this reference within all callbacks is the object in the context opt ion passed to $ajax in thesett ings if context is not specif ied this is a reference to the Ajax sett ings themselves

      Some types of Ajax requests such as JSONP and cross-domain GET requests do not useXHR in those cases the XMLHttpRequest and textStatus parameters passed to the callbackare undef ined

      Here are the callback hooks provided by $ajax()

      1 beforeSend callback is invoked it receives the jqXHR object and the sett ings map asparameters

      2 error callbacks are invoked in the order they are registered if the request fails Theyreceive the jqXHR a string indicat ing the error type and an except ion object if applicableSome built -in errors will provide a string as the except ion object abort t imeout NoTransport

      3 dataFilter callback is invoked immediately upon successful receipt of response data Itreceives the returned data and the value of dataType and must return the (possiblyaltered) data to pass on to success

      4 success callbacks are then invoked in the order they are registered if the requestsucceeds They receive the returned data a string containing the success code and thejqXHR object

      5 complete callbacks f ire in the order they are registered when the request f inisheswhether in failure or success They receive the jqXHR object as well as a string containingthe success or error code

      For example to make use of the returned HTML we can implement a success handler

      $ajax( url ajaxtesthtml success function(data) $( result)html(data) alert(Load was performed) )

      Data Types

      The $ajax() funct ion relies on the server to provide informat ion about the retrieved data If theserver reports the return data as XML the result can be traversed using normal XML methodsor jQuerys selectors If another type is detected such as HTML in the example above the datais t reated as text

      Dif ferent data handling can be achieved by using the dataType opt ion Besides plain xml thedataType can be html json jsonp script or text

      The text and xml types return the data with no processing The data is simply passed on to thesuccess handler either through the responseText or responseXML property of the jqXHRobject respect ively

      Note We must ensure that the MIME type reported by the web server matches our choice ofdataType In part icular XML must be declared by the server as text xml or applicat ionxml forconsistent results

      If html is specif ied any embedded JavaScript inside the retrieved data is executed before theHTML is returned as a string Similarly script will execute the JavaScript that is pulled back fromthe server then return nothing

      The json type parses the fetched data f ile as a JavaScript object and returns the constructedobject as the result data To do so it uses jQueryparseJSON() when the browser supports it

      otherwise it uses a Funct ion constructor Malformed JSON data will throw a parse error (seejsonorg for more informat ion) JSON data is convenient for communicat ing structured data in away that is concise and easy for JavaScript to parse If the fetched data f ile exists on a remoteserver specify the jsonp type instead

      The jsonp type appends a query string parameter of callback= to the URL The server shouldprepend the JSON data with the callback name to form a valid JSONP response We canspecify a parameter name other than callback with the jsonp opt ion to $ajax()

      Note JSONP is an extension of the JSON format requiring some server-side code to detectand handle the query string parameter More informat ion about it can be found in the originalpost detailing its use

      When data is retrieved from remote servers (which is only possible using the script or jsonpdata types) the error callbacks and global events will never be f ired

      Sending Data to the Server

      By default Ajax requests are sent using the GET HTTP method If the POST method isrequired the method can be specif ied by sett ing a value for the type opt ion This opt ionaffects how the contents of the data opt ion are sent to the server POST data will always betransmit ted to the server using UTF-8 charset per the W3C XMLHTTPRequest standard

      The data opt ion can contain either a query string of the form key1=value1ampkey2=value2 or amap of the form key1 value1 key2 value2 If the lat ter form is used the data is convertedinto a query string using jQueryparam() before it is sent This processing can be circumventedby sett ing processData to false The processing might be undesirable if you wish to send anXML object to the server in this case change the contentType opt ion f rom applicat ionx-www-form-urlencoded to a more appropriate MIME type

      Advanced Options

      The global opt ion prevents handlers registered using ajaxSend() ajaxError() and similarmethods from f iring when this request would t rigger them This can be useful to for examplesuppress a loading indicator that was implemented with ajaxSend() if the requests are f requentand brief With cross-domain script and JSONP requests the global opt ion is automat ically setto false See the descript ions of these methods below for more details See the descript ions ofthese methods below for more details

      If the server performs HTTP authent icat ion before providing a response the user name andpassword pair can be sent via the username and password opt ions

      Ajax requests are t ime-limited so errors can be caught and handled to provide a better userexperience Request t imeouts are usually either lef t at their default or set as a global defaultusing $ajaxSetup() rather than being overridden for specif ic requests with the t imeout opt ion

      By default requests are always issued but the browser may serve results out of its cache Todisallow use of the cached results set cache to false To cause the request to report failure ifthe asset has not been modif ied since the last request set ifModif ied to t rue

      The scriptCharset allows the character set to be explicit ly specif ied for requests that use altscriptgt tag (that is a type of script or jsonp) This is useful if the script and host page havedif fering character sets

      The f irst let ter in Ajax stands for asynchronous meaning that the operat ion occurs in paralleland the order of complet ion is not guaranteed The async opt ion to $ajax() defaults to t rueindicat ing that code execut ion can cont inue af ter the request is made Sett ing this opt ion tofalse (and thus making the call no longer asynchronous) is strongly discouraged as it can causethe browser to become unresponsive

      The $ajax() funct ion returns the XMLHttpRequest object that it creates Normally jQueryhandles the creat ion of this object internally but a custom funct ion for manufacturing one canbe specif ied using the xhr opt ion The returned object can generally be discarded but doesprovide a lower-level interface for observing and manipulat ing the request In part icular callingabort() on the object will halt the request before it completes

      Extending Ajax

      As of jQuery 15 jQuerys Ajax implementat ion includes pref ilters converters and transportsthat allow you to extend Ajax with a great deal of f lexibility For more informat ion about theseadvanced features see the Extending Ajax page

      Example 1 Load and execute a JavaScript f ile

      Javascript

      $ajax( type GET url testjs dataType script )

      Example 2 Save some data to the server and not ify the user once it s complete

      Javascript

      $ajax( type POST url somephp data name=Johnamplocation=Boston success function(msg) alert( Data Saved + msg ) )

      Example 3 Retrieve the latest version of an HTML page

      Javascript

      $ajax( url testhtml cache false success function(html) $(results)append(html) )

      Example 4 Loads data synchronously Blocks the browser while the requests is act ive It isbetter to block user interact ion by other means when synchronizat ion is necessary

      Javascript

      var html = $ajax( url somephp async false )responseText

      Example 5 Sends an xml document as data to the server By sett ing the processData opt ion tofalse the automat ic conversion of data to strings is prevented

      Javascript

      var xmlDocument = [create xml document] $ajax( url pagephp processData false data xmlDocument success handleResponse )

      Example 6 Sends an id as data to the server save some data to the server and not ify the useronce it s complete Note that this usage - returning the result of the call into a variable -

      requires a synchronous (blocking) request (asyncfalse)

      Javascript

      var bodyContent = $ajax( url scriptphp global false type POST data id thisgetAttribute( id) dataType html asyncfalse success function(msg) alert(msg) )responseText

      jQueryparam see Forms

      Miscellaneous

      each see Traversing

      toArray

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

      Added in version 14

      toArray()Array

      toArray() returns all of the elements in the jQuery set

      alert($( l i )toArray())

      All of the matched DOM nodes are returned by this call contained in a standard array

      [ltli id=foogt ltli id=bargt]

      Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

      Javascript

      function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)toArray()reverse() )

      CSS

      span colorred

      HTML

      Reversed - ltspangtltspangt

      ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

      index

      Search for a given element f rom among the matched elements

      Added in version 10

      index(element)Number

      elementElementjQuery

      The DOM element or f irst element within the jQuery object tolook for

      Return Values

      If no argument is passed to the index() method the return value is an integer indicat ing theposit ion of the f irst element within the jQuery object relat ive to its sibling elements

      If index() is called on a collect ion of elements and a DOM element or jQuery object is passed inindex() returns an integer indicat ing the posit ion of the passed element relat ive to the originalcollect ion

      If a selector string is passed as an argument index() returns an integer indicat ing the posit ionof the original element relat ive to the elements matched by the selector If the element is notfound index() will return -1

      Detail

      The complementary operat ion to get() which accepts an index and returns a DOM nodeindex() can take a DOM node and returns an index Suppose we have a simple unordered list onthe page

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgt

      If we retrieve one of the three list items (for example through a DOM funct ion or as thecontext to an event handler) index() can search for this list item within the set of matchedelements

      var l istItem = documentgetElementById(bar)alert( Index + $( l i )index(l istItem))We get back the zero-based position of the l ist item

      Index 1

      Similarly if we retrieve a jQuery object consist ing of one of the three list items index() willsearch for that list item

      var l istItem = $(bar)alert( Index + $( l i )index(l istItem))

      We get back the zero-based posit ion of the list item

      Index 1

      Note that if the jQuery collect ion used as the index() methods argument contains more thanone element the f irst element within the matched set of elements will be used

      var l istItems = $( l i gt(0))alert( Index + $( l i )index(l istItems))

      We get back the zero-based posit ion of the f irst list item within the matched set

      Index 1

      If we use a string as the index() methods argument it is interpreted as a jQuery selector string

      The f irst element among the object s matched elements which also matches this selector islocated

      var l istItem = $(bar)alert( Index + l istItemindex( l i ))

      We get back the zero-based posit ion of the list item

      Index 1

      If we omit the argument index() will return the posit ion of the f irst element within the set ofmatched elements in relat ion to its siblings

      alert( Index + $(bar)index()

      Again we get back the zero-based posit ion of the list item

      Index 1

      Example 1 On click returns the index (based zero) of that div in the page

      Javascript

      $(div)cl ick(function () this is the dom element cl icked var index = $(div)index(this) $(span)text(That was div index + index))

      CSS

      div backgroundyellow margin5px span colorred

      HTML

      ltspangtClick a divltspangtltdivgtFirst divltdivgtltdivgtSecond divltdivgtltdivgtThird divltdivgt

      Example 2 Returns the index for the element with ID bar

      CSS

      div font-weight bold color 090

      Javascript

      var l istItem = $(bar) $(div)html( Index + $( l i )index(l istItem) )

      HTML

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

      Example 3 Returns the index for the f irst item in the jQuery collect ion

      CSS

      div font-weight bold color 090

      Javascript

      var l istItems = $( l i gt(0))$(div)html( Index + $( l i )index(l istItems) )

      HTML

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

      Example 4 Returns the index for the element with ID bar in relat ion to all

      elements

      CSS

      div font-weight bold color 090

      Javascript

      $(div)html( Index + $(bar)index( l i ) )

      HTML

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

      Example 5 Returns the index for the element with ID bar in relat ion to its siblings

      CSS

      div font-weight bold color 090

      Javascript

      var barIndex = $(bar)index()$(div)html( Index + barIndex )

      HTML

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

      Example 6 Returns -1 as there is no element with ID foobar

      CSS

      div font-weight bold color 090

      Javascript

      var foobar = $(l i)index( $(foobar) )$(div)html( Index + foobar)

      HTML

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

      removeData see Data

      data see Data

      data see Data

      get

      Retrieve the DOM elements matched by the jQuery object

      Added in version 10

      get(index)Element Array

      indexNumber (opt ional) A zero-based integer indicat ing which element to retrieve

      The get() method grants us access to the DOM nodes underlying each jQuery object Supposewe had a simple unordered list on the page

      ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligtltulgt

      Without a parameter get() returns all of the elements

      alert($( l i )get())

      All of the matched DOM nodes are returned by this call contained in a standard array

      [ltli id=foogt ltli id=bargt]

      With an index specif ied get() will retrieve a single element

      ($( l i )get(0))

      Since the index is zero-based the f irst list item is returned

      ltli id=foogt

      Each jQuery object also masquerades as an array so we can use the array dereferencingoperator to get at the list item instead

      alert($( l i )[0])

      However this syntax lacks some of the addit ional capabilit ies of get() such as specifying anegat ive index

      alert($( l i )get(-1))

      A negat ive index is counted from the end of the matched set so this example will return thelast item in the list

      ltli id=bargt

      Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

      Javascript

      function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)get()reverse() )

      CSS

      span colorred

      HTML

      Reversed - ltspangtltspangt

      ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

      Example 2 Gives the tag name of the element clicked on

      Javascript

      $( documentbody)cl ick(function (e) estopPropagation() var domEl = $(this)get(0) $(spanfirst)text(Clicked on - + domEltagName) )

      CSS

      span colorred div backgroundyellow

      HTML

      ltspangtampnbspltspangt ltpgtIn this paragraph is an ltspangtimportantltspangt sectionltpgt

      ltdivgtltinput type=text gtltdivgt

      size

      Return the number of elements in the jQuery object

      Added in version 10

      size()Number

      The size() method is funct ionally equivalent to the length property however the lengthproperty is preferred because it does not have the overhead of a funct ion call

      Given a simple unordered list on the page

      ltulgt ltligtfooltligt ltligtbarltligtltulgt

      Both size() and length ident ify the number of items

      alert( Size + $(l i)size() )alert( Size + $(l i)length )

      This results in two alerts

      Size 2

      Size 2

      Example 1 Count the divs Click to add more

      Javascript

      $(documentbody)cl ick(function() $(this)append( $(ltdivgt) ) var n = $(div)size() $(span)text(There are + n + divs Click to add more)) trigger the cl ick to startcl ick()

      CSS

      body cursorpointer min-height 100px div width50px height30px margin5px floatleft backgroundblue span colorred

      HTML

      ltspangtltspangt ltdivgtltdivgt

      jQuerynoConflict see Core

      jQueryparam see Forms

      Dimensions

      outerWidth see CSS

      outerHeight see CSS

      innerWidth see CSS

      innerHeight see CSS

      width see CSS

      width see CSS

      height see CSS

      height see CSS

      Offset

      offsetParent see Traversing

      scrollLeft see CSS

      scrollLeft see CSS

      scrollTop see CSS

      scrollTop see CSS

      position see CSS

      offset see CSS

      offset see CSS

      Utilities

      jQuerynow

      Return a number represent ing the current t ime

      Added in version 143

      jQuerynow()Number

      The $now() method is a shorthand for the number returned by the expression (newDate)getTime()

      jQueryparseXML

      Parses a string into an XML document

      Added in version 15

      jQueryparseXML(data)XMLDocument

      dataString a well-formed XML string to be parsed

      jQueryparseXML uses the nat ive parsing funct ion of the browser to create a valid XMLDocument This document can then be passed to jQuery to create a typical jQuery object thatcan be traversed and manipulated

      Example 1 Create a jQuery object using an XML string and obtain the value of the t it le node

      HTML

      ltp id=someElementgtltpgtltp id=anotherElementgtltpgt

      Javascript

      var xml = ltrss version=20gtltchannelgtlttitlegtRSS Titlelttitlegtltchannelgtltrssgt xmlDoc = $parseXML( xml ) $xml = $( xmlDoc ) $title = $xmlfind( title )

      append RSS Title to someElement $( someElement )append( $titletext() )

      change the title to XML Title $titletext( XML Title )

      append XML Title to anotherElement $( anotherElement )append( $titletext() )

      jQuerytype

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

      Added in version 143

      jQuerytype(obj)String

      objObject 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

      If the object is undef ined or null then undef ined or null is returned accordingly

      If the object has an internal [[Class]] equivalent to one of the browsers built -in objectsthe associated name is returned (More details about this technique)

      jQuerytype(true) === boolean

      jQuerytype(3) === number

      jQuerytype(test) === string

      jQuerytype(funct ion()) === funct ion

      jQuerytype([]) === array

      jQuerytype(new Date()) === date

      jQuerytype(test ) === regexp

      Everything else returns object as its type

      Example 1 Find out if the parameter is a RegExp

      Javascript

      $(b)append( + jQuerytype(test) )

      HTML

      Is it a RegExp ltbgtltbgt

      jQueryisWindow

      Determine whether the argument is a window

      Added in version 143

      jQueryisWindow(obj)boolean

      objObject Object to test whether or not it is a window

      This is used in a number of places in jQuery to determine if were operat ing against a browserwindow (such as the current window or an if rame)

      Example 1 Finds out if the parameter is a window

      Javascript

      $(b)append( + $isWindow(window) )

      HTML

      Is window a window ltbgtltbgt

      jQueryparseJSON

      Takes a well-formed JSON string and returns the result ing JavaScript object

      Added in version 141

      jQueryparseJSON(json)Object

      jsonString The JSON string to parse

      Passing in a malformed JSON string may result in an except ion being thrown For example thefollowing are all malformed JSON strings

      test 1 (test does not have double quotes around it )

      test 1 (test is using single quotes instead of double quotes)

      Addit ionally if you pass in nothing an empty string null or undef ined null will be returned fromparseJSON Where the browser provides a nat ive implementat ion of JSONparse jQuery uses itto parse the string For details on the JSON format see ht tpjsonorg

      Example 1 Parse a JSON string

      Javascript

      var obj = jQueryparseJSON(nameJohn)alert( objname === John )

      jQueryproxy see Events

      jQuerycontains

      Check to see if a DOM element is within another DOM element

      Added in version 14

      jQuerycontains(container contained)Boolean

      containerElement The DOM element that may contain the other element

      containedElement The DOM element that may be contained by the other element

      Example 1 Check if an element is inside another Text and comment nodes are not supported

      Javascript

      jQuerycontains(documentdocumentElement documentbody) truejQuerycontains(documentbody documentdocumentElement) false

      jQuerynoop

      An empty funct ion

      Added in version 14

      jQuerynoop()Funct ion

      You can use this empty funct ion when you wish to pass around a funct ion that will do nothing

      This is useful for plugin authors who of fer opt ional callbacks in the case that no callback isgiven something like jQuerynoop could execute

      jQueryglobalEval

      Execute some JavaScript code globally

      Added in version 104

      jQueryglobalEval(code)

      codeString The JavaScript code to execute

      This method behaves dif ferent ly f rom using a normal JavaScript eval() in that it s executedwithin the global context (which is important for loading external scripts dynamically)

      Example 1 Execute a script in the global context

      Javascript

      function test() jQueryglobalEval(var newVar = true)test() newVar === true

      jQueryisXMLDoc

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

      Added in version 114

      jQueryisXMLDoc(node)Boolean

      nodeElement The DOM node that will be checked to see if it s in an XML document

      Example 1 Check an object to see if it s in an XML document

      Javascript

      jQueryisXMLDoc(document) falsejQueryisXMLDoc(documentbody) false

      jQueryremoveData see Data

      jQuerydata see Data

      jQuerydata see Data

      jQuerydequeue see Data

      jQueryqueue see Data

      jQueryqueue see Data

      clearQueue see Data

      jQueryisEmptyObject

      Check to see if an object is empty (contains no propert ies)

      Added in version 14

      jQueryisEmptyObject(object)Boolean

      object Object The object that will be checked to see if it s empty

      As of jQuery 14 this method checks both propert ies on the object itself and propert iesinherited f rom prototypes (in that it doesnt use hasOwnProperty) The argument shouldalways be a plain JavaScript Object as other types of object (DOM elements primit ivestringsnumbers host objects) may not give consistent results across browsers To determine ifan object is a plain JavaScript object use $isPlainObject()

      Example 1 Check an object to see if it s empty

      Javascript

      jQueryisEmptyObject() truejQueryisEmptyObject( foo bar ) false

      jQueryisPlainObject

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

      Added in version 14

      jQueryisPlainObject(object)Boolean

      object Object The object that will be checked to see if it s a plain object

      Note Host objects (or objects used by browser host environments to complete the execut ionenvironment of ECMAScript) have a number of inconsistencies which are dif f icult to robust lyfeature detect cross-plat form As a result of this $isPlainObject() may evaluate inconsistent lyacross browsers in certain instances

      An example of this is a test against documentlocat ion using $isPlainObject() as follows

      consolelog($isPlainObject(documentlocation))

      which throws an invalid pointer except ion in IE8 With this in mind it s important to be aware ofany of the gotchas involved in using $isPlainObject() against older browsers Some basicexample of use-cases that do funct ion correct ly cross-browser can be found below

      Example 1 Check an object to see if it s a plain object

      Javascript

      jQueryisPlainObject() truejQueryisPlainObject(test) false

      dequeue see Data

      queue see Data

      queue see Data

      jQuerybrowser

      Contains f lags for the useragent read from navigatoruserAgent We recommend against usingthis property please try to use feature detect ion instead (see jQuerysupport) jQuerybrowsermay be moved to a plugin in a future release of jQuery

      Added in version 10

      The $browser property provides informat ion about the web browser that is accessing thepage as reported by the browser itself It contains f lags for each of the four most prevalentbrowser classes (Internet Explorer Mozilla Webkit and Opera) as well as version informat ion

      Available f lags are

      webkit (as of jQuery 14)

      safari (deprecated)

      opera

      msie

      mozilla

      This property is available immediately It is therefore safe to use it to determine whether or notto call $(document)ready() The $browser property is deprecated in jQuery 13 and itsfunct ionality may be moved to a team-supported plugin in a future release of jQuery

      Because $browser uses navigatoruserAgent to determine the plat form it is vulnerable tospoof ing by the user or misrepresentat ion by the browser itself It is always best to avoidbrowser-specif ic code ent irely where possible The $support property is available for detect ionof support for part icular features rather than relying on $browser

      Example 1 Show the browser info

      Javascript

      jQueryeach(jQuerybrowser function(i val) $(ltdivgt + i + ltspangt + val + ltspangt) appendTo( documentbody ) )

      CSS

      p colorgreen font-weightbolder margin3px 0 0 10px div colorblue margin-left20px font-size14px span colorred

      HTML

      ltpgtBrowser infoltpgt

      Example 2 Returns t rue if the current useragent is some version of Microsoft s InternetExplorer

      Javascript

      $browsermsie

      Example 3 Alerts this is WebKit only for WebKit browsers

      Javascript

      i f ($browserwebkit) alert( this is webkit )

      Example 4 Alerts Do stuf f for Firefox 3 only for Firefox 3 browsers

      Javascript

      var ua = $browser i f ( uamozil la ampamp uaversionsl ice(03) == 19 ) alert( Do stuff for firefox 3 )

      Example 5 Set a CSS property that s specif ic to a part icular browser

      Javascript

      i f ( $browsermsie ) $(div ul l i)css( display inl ine ) else $(div ul l i)css( display inl ine-table )

      jQuerybrowserversion

      The version number of the rendering engine for the users browser

      Added in version 113

      Here are some typical results

      Internet Explorer 60 70 80

      MozillaFirefoxFlockCamino 1712 1813 19

      Opera 1006 1101

      SafariWebkit 3128 4189

      Note that IE8 claims to be 7 in Compat ibility View

      Example 1 Returns the version number of the rendering engine used by the users currentbrowser For example FireFox 4 returns 20 (the version of the Gecko rendering engine itut ilizes)

      Javascript

      $(p)html( The version number of the rendering engine your browser uses is ltspangt + $browserversion + ltspangt )

      CSS

      p colorblue margin20px span colorred

      HTML

      ltpgtltpgt

      Example 2 Alerts the version of IEs rendering engine that is being used

      Javascript

      i f ( $browsermsie ) alert( $browserversion )

      Example 3 Often you only care about the major number the whole number which you canget by using JavaScript s built -in parseInt() funct ion

      Javascript

      i f ( $browsermsie ) alert( parseInt($browserversion 10) )

      jQuerytrim

      Remove the whitespace from the beginning and end of a string

      Added in version 10

      jQueryt rim(str)String

      strString The string to t rim

      The $t rim() funct ion removes all newlines spaces (including non-breaking spaces) and tabsfrom the beginning and end of the supplied string If these whitespace characters occur in themiddle of the string they are preserved

      Example 1 Remove the two white spaces at the start and at the end of the string

      Javascript

      $(button)cl ick(function () var str = lots of spaces before and after alert( + str + )

      str = jQuerytrim(str)alert( + str + - no longer))

      HTML

      ltbuttongtShow Trim Exampleltbuttongt

      Example 2 Remove the two white spaces at the start and at the end of the string

      Javascript

      $trim( hello how are you )

      Results

      hello how are you

      jQueryisFunction

      Determine if the argument passed is a Javascript funct ion object

      Added in version 12

      jQueryisFunct ion(obj)boolean

      objObject Object to test whether or not it is a funct ion

      Note As of jQuery 13 funct ions provided by the browser like alert() and DOM elementmethods like getAttribute() are not guaranteed to be detected as funct ions in browsers suchas Internet Explorer

      Example 1 Test a few parameter examples

      Javascript

      function stub() var objs = [ function () x15 y20 null stub function ]

      jQueryeach(objs function (i) var isFunc = jQueryisFunction(objs[i]) $(span)eq(i)text(isFunc) )

      CSS

      div colorblue margin2px font-size14px span colorred

      HTML

      ltdivgtjQueryisFunction(objs[0]) = ltspangtltspangtltdivgt

      ltdivgtjQueryisFunction(objs[1]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[2]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[3]) = ltspangtltspangtltdivgt

      ltdivgtjQueryisFunction(objs[4]) = ltspangtltspangtltdivgt

      Example 2 Finds out if the parameter is a funct ion

      Javascript

      $isFunction(function())

      Results

      true

      jQueryisArray

      Determine whether the argument is an array

      Added in version 13

      jQueryisArray(obj)boolean

      objObject Object to test whether or not it is an array

      $isArray() returns a Boolean indicat ing whether the object is a JavaScript array (not an array-like object such as a jQuery object)

      Example 1 Finds out if the parameter is an array

      Javascript

      $(b)append( + $isArray([]) )

      HTML

      Is [] an Array ltbgtltbgt

      jQueryunique

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

      Added in version 113

      jQueryunique(array)Array

      arrayArray The Array of DOM elements

      The $unique() funct ion searches through an array of objects sort ing the array and removingany duplicate nodes This funct ion only works on plain JavaScript arrays of DOM elements andis chief ly used internally by jQuery

      As of jQuery 14 the results will always be returned in document order

      Example 1 Removes any duplicate elements f rom the array of divs

      Javascript

      var divs = $(div)get() unique() must take a native array

      add 3 elements of class dup too (they are divs) divs = divsconcat($(dup)get()) $(diveq(1))text(Pre-unique there are + divslength + elements)

      divs = jQueryunique(divs) $(diveq(2))text(Post-unique there are + divslength + elements) css(color red)

      CSS

      div colorblue

      HTML

      ltdivgtThere are 6 divs in this documentltdivgt ltdivgtltdivgt ltdiv class=dupgtltdivgt ltdiv class=dupgtltdivgt

      ltdiv class=dupgtltdivgt ltdivgtltdivgt

      jQuerymerge

      Merge the contents of two arrays together into the f irst array

      Added in version 10

      jQuerymerge(f irst second)Array

      f irst Array The f irst array to merge the elements of second added

      secondArray The second array to merge into the f irst unaltered

      The $merge() operat ion forms an array that contains all elements f rom the two arrays Theorders of items in the arrays are preserved with items from the second array appended The$merge() funct ion is destruct ive It alters the f irst parameter to add the items from the second

      If you need the original f irst array make a copy of it before calling $merge() Fortunately$merge() itself can be used for this duplicat ion

      var newArray = $merge([] oldArray)

      This shortcut creates a new empty array and merges the contents of oldArray into it ef fect ively cloning the array

      Prior to jQuery 14 the arguments should be true Javascript Array objects use $makeArray ifthey are not

      Example 1 Merges two arrays altering the f irst argument

      Javascript

      $merge( [012] [234] )

      Results

      [012234]

      Example 2 Merges two arrays altering the f irst argument

      Javascript

      $merge( [321] [432] )

      Results

      [321432]

      Example 3 Merges two arrays but uses a copy so the original isnt altered

      Javascript

      var first = [abc]var second = [de f]$merge( $merge([]first) second)

      Results

      [abcdef]

      jQueryinArray

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

      Added in version 12

      jQueryinArray(value array)Number

      valueAny The value to search for

      arrayArray An array through which to search

      The $inArray() method is similar to JavaScript s nat ive indexOf() method in that it returns -1when it doesnt f ind a match If the f irst element within the array matches value $inArray()returns 0

      Because JavaScript t reats 0 as loosely equal to false (ie 0 == false but 0 == false) if werechecking for the presence of value within array we need to check if it s not equal to (or greaterthan) -1

      Example 1 Report the index of some elements in the array

      Javascript

      var arr = [ 4 Pete 8 John ]

      $(spaneq(0))text(jQueryinArray(John arr))$(spaneq(1))text(jQueryinArray(4 arr))$(spaneq(2))text(jQueryinArray(Karl arr))

      CSS

      div colorblue span colorred

      HTML

      ltdivgtJohn found at ltspangtltspangtltdivgtltdivgt4 found at ltspangtltspangtltdivgtltdivgtKarl not found so ltspangtltspangtltdivgt

      jQuerymap

      Translate all items in an array or object to new array of items

      Added in version 16

      jQuerymap(arrayOrObject callback( value indexOrKey ))Array

      arrayOrObject ArrayObject The Array or Object to t ranslate

      callback( value indexOrKey)Funct ion

      The funct ion to process each item against The f irstargument to the funct ion is the value the secondargument is the index or key of the array or objectproperty The funct ion can return any value to add to thearray A returned array will be f lat tened into the result ingarray Within the funct ion this refers to the global (window)object

      The $map() method applies a funct ion to each item in an array or object and maps the resultsinto a new array Prior to jQuery 16 $map() supports t raversing arrays only As of jQuery 16 italso t raverses objects

      Array-like objects acirceurordquo those with a length property and a value on the length - 1 index acirceurordquo mustbe converted to actual arrays before being passed to $map() The jQuery library provides$makeArray() for such conversions

      The following object masquerades as an arrayvar fakeArray = length 1 0 Addy 1 Subtracty

      Therefore convert it to a real arrayvar realArray = $makeArray( fakeArray )

      Now it can be used reliably with $map()$map( realArray function(val i) do something )

      The translat ion funct ion that is provided to this method is called for each top-level element inthe array or object and is passed two arguments The element s value and its index or keywithin the array or object

      The funct ion can return

      the translated value which will be mapped to the result ing array

      null to remove the item

      an array of values which will be f lat tened into the full array

      Example 1 A couple examples of using map()

      Javascript

      var arr = [ a b c d e ] $(div)text(arrjoin( ))

      arr = jQuerymap(arr function(n i) return (ntoUpperCase() + i) ) $(p)text(arrjoin( ))

      arr = jQuerymap(arr function (a) return a + a ) $(span)text(arrjoin( ))

      CSS

      div colorblue p colorgreen margin0 span colorred

      HTML

      ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

      Example 2 Map the original array to a new one and add 4 to each value

      Javascript

      $map( [012] function(n) return n + 4 )

      Results

      [4 5 6]

      Example 3 Maps the original array to a new one and adds 1 to each value if it is bigger thenzero otherwise it s removed

      Javascript

      $map( [012] function(n) return n gt 0 n + 1 null )

      Results

      [2 3]

      Example 4 Map the original array to a new one each element is added with its original valueand the value plus one

      Javascript

      $map( [012] function(n) return [ n n + 1 ] )

      Results

      [0 1 1 2 2 3]

      Example 5 Map the original object to a new array and double each value

      Javascript

      var dimensions = width 10 height 15 length 20 dimensions = $map( dimensions function( value index ) return value 2)

      Results

      [20 30 40]

      Example 6 Map an object s keys to an array

      Javascript

      var dimensions = width 10 height 15 length 20 keys = $map( dimensions function( value index ) return index )

      Results

      [width height length]

      Example 7 Maps the original array to a new one each element is squared

      Javascript

      $map( [0123] function (a) return a a )

      Results

      [0 1 4 9]

      Example 8 Remove items by returning null f rom the funct ion This removes any numbers lessthan 50 and the rest are decreased by 45

      Javascript

      $map( [0 1 52 97] function (a) return (a gt 50 a - 45 null) )

      Results

      [7 52]

      Example 9 Augment ing the result ing array by returning an array inside the funct ion

      Javascript

      var array = [0 1 52 97]array = $map(array function(a index) return [a - 45 index])

      Results

      [-45 0 -44 1 7 2 52 3]

      jQuerymakeArray

      Convert an array-like object into a t rue JavaScript array

      Added in version 12

      jQuerymakeArray(obj)Array

      objObject Any object to turn into a nat ive Array

      Many methods both in jQuery and in JavaScript in general return objects that are array-like Forexample the jQuery factory funct ion $() returns a jQuery object that has many of thepropert ies of an array (a length the [] array access operator etc) but is not exact ly the sameas an array and lacks some of an arrays built -in methods (such as pop() and reverse())

      Note that af ter the conversion any special features the object had (such as the jQuerymethods in our example) will no longer be present The object is now a plain array

      Example 1 Turn a collect ion of HTMLElements into an Array of them

      Javascript

      var elems = documentgetElementsByTagName(div) returns a nodeList var arr = jQuerymakeArray(elems) arrreverse() use an Array method on l ist of dom elements $(arr)appendTo(documentbody)

      CSS

      div colorred

      HTML

      ltdivgtFirstltdivgt ltdivgtSecondltdivgt ltdivgtThirdltdivgt

      ltdivgtFourthltdivgt

      Example 2 Turn a jQuery object into an array

      Javascript

      var obj = $( l i ) var arr = $makeArray(obj)

      Results

      (typeof obj === object ampamp objjquery) === truejQueryisArray(arr) === true

      jQuerygrep

      Finds the elements of an array which sat isfy a f ilter funct ion The original array is not af fected

      Added in version 10

      jQuerygrep(array funct ion(elementOfArray indexInArray) invert)Array

      arrayArray The array to search through

      funct ion(elementOfArrayindexInArray)Funct ion

      The funct ion to process each item against The f irstargument to the funct ion is the item and the secondargument is the index The funct ion should return a Booleanvalue this will be the global window object

      invert Boolean (opt ional) If invert is false or not provided then thefunct ion returns an array consist ing of all elements for whichcallback returns t rue If invert is t rue then the funct ionreturns an array consist ing of all elements for whichcallback returns false

      The $grep() method removes items from an array as necessary so that all remaining items passa provided test The test is a funct ion that is passed an array item and the index of the itemwithin the array Only if the test returns t rue will the item be in the result array

      The f ilter funct ion will be passed two arguments the current array item and its index The f ilterfunct ion must return t rue to include the item in the result array

      Example 1 Filters the original array of numbers leaving that are not 5 and have an index greaterthan 4 Then it removes all 9s

      Javascript

      var arr = [ 1 9 3 8 6 1 5 9 4 7 3 8 6 9 1 ]$(div)text(arrjoin( ))

      arr = jQuerygrep(arr function(n i) return (n = 5 ampamp i gt 4))$(p)text(arrjoin( ))

      arr = jQuerygrep(arr function (a) return a = 9 )$(span)text(arrjoin( ))

      CSS

      div colorblue p colorgreen margin0 span colorred

      HTML

      ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

      Example 2 Filter an array of numbers to include only numbers bigger then zero

      Javascript

      $grep( [012] function(ni) return n gt 0 )

      Results

      [1 2]

      Example 3 Filter an array of numbers to include numbers that are not bigger than zero

      Javascript

      $grep( [012] function(ni) return n gt 0true)

      Results

      [0]

      jQueryextend

      Merge the contents of two or more objects together into the f irst object

      Added in version 114

      jQueryextend(deep target object1 objectN)Object

      deepBoolean (opt ional) If t rue the merge becomes recursive (aka deep copy)

      targetObject The object to extend It will receive the new propert ies

      object1Object An object containing addit ional propert ies to merge in

      objectNObject (opt ional) Addit ional objects containing propert ies to merge in

      When we supply two or more objects to $extend() propert ies f rom all of the objects are addedto the target object

      If only one argument is supplied to $extend() this means the target argument was omit ted Inthis case the jQuery object itself is assumed to be the target By doing this we can add newfunct ions to the jQuery namespace This can be useful for plugin authors wishing to add newmethods to JQuery

      Keep in mind that the target object (f irst argument) will be modif ied and will also be returnedfrom $extend() If however we want to preserve both of the original objects we can do so bypassing an empty object as the target

      var object = $extend( object1 object2)

      The merge performed by $extend() is not recursive by default if a property of the f irst object isitself an object or array it will be completely overwrit ten by a property with the same key in thesecond object The values are not merged This can be seen in the example below by examiningthe value of banana However by passing true for the f irst funct ion argument objects will berecursively merged

      Undef ined propert ies are not copied However propert ies inherited f rom the object s prototypewill be copied over For performance reasons propert ies that have values of built -in JavaScripttypes such as Date or RegExp are not re-constructed and will appear as plain Objects in theresult ing object or array

      Note When performing a deep extend Object and Array are extended howeverprimitive types such string boolean and number are not For specific needs thatfall outside of this behaviour it is recommended to write a custom extend methodas this will be significantly faster from a performance perspective

      Example 1 Merge two objects modifying the f irst

      Javascript

      var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

      merge object2 into object1 $extend(object1 object2)

      var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

      $(log)append( printObj(object1) )

      HTML

      ltdiv id=loggtltdivgt

      Example 2 Merge two objects recursively modifying the f irst

      Javascript

      var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

      merge object2 into object1 recursively $extend(true object1 object2)

      var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

      $(log)append( printObj(object1) )

      HTML

      ltdiv id=loggtltdivgt

      Example 3 Merge defaults and opt ions without modifying the defaults This is a commonplugin development pattern

      Javascript

      var defaults = validate false l imit 5 name foo var options = validate true name bar

      merge defaults and options without modifying defaults var settings = $extend( defaults options)

      var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

      $(log)append( ltdivgtltbgtsettings -- ltbgt + printObj(settings) + ltdivgt )$(log)append( ltdivgtltbgtoptions -- ltbgt + printObj(options) + ltdivgt )

      HTML

      ltdiv id=loggtltdivgt

      jQueryeach

      A generic iterator funct ion which can be used to seamlessly iterate over both objects andarrays Arrays and array-like objects with a length property (such as a funct ions argumentsobject) are iterated by numeric index f rom 0 to length-1 Other objects are iterated via theirnamed propert ies

      Added in version 10

      jQueryeach(collect ion callback(indexInArray valueOfElement))Object

      collect ionObject The object or array to iterate over

      callback(indexInArrayvalueOfElement)Funct ion

      The funct ion that will be executed on everyobject

      The $each() funct ion is not the same as $(selector)each() which is used to iterate exclusivelyover a jQuery object The $each() funct ion can be used to iterate over any collect ion whetherit is a map (JavaScript object) or an array In the case of an array the callback is passed an arrayindex and a corresponding array value each t ime (The value can also be accessed through the

      this keyword but Javascript will always wrap the this value as an Object even if it is a simplestring or number value) The method returns its f irst argument the object that was iterated

      $each([52 97] function(index value) alert(index + + value) )

      This produces two messages

      0 52

      1 97

      If a map is used as the collect ion the callback is passed a key-value pair each t ime

      var map = flammable inflammable duh no duh $each(map function(key value) alert(key + + value) )

      Once again this produces two messages

      f lammable inf lammable

      duh no duh

      We can break the $each() loop at a part icular iterat ion by making the callback funct ion returnfalse Returning non-false is the same as a cont inue statement in a for loop it will skipimmediately to the next iterat ion

      Example 1 Iterates through the array displaying each number as both a word and numeral

      Javascript

      var arr = [ one two three four five ] var obj = one1 two2 three3 four4 five5

      jQueryeach(arr function() $( + this)text(Mine is + this + ) return (this = three) wil l stop running after three )

      jQueryeach(obj function(i val) $( + i)append(documentcreateTextNode( - + val)) )

      CSS

      div colorblue divfive colorred

      HTML

      ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt ltdiv id=fourgtltdivgt ltdiv id=fivegtltdivgt

      Example 2 Iterates over items in an array accessing both the current item and its index

      Javascript

      $each( [abc] function(i l) alert( Index + i + + l ) )

      Example 3 Iterates over the propert ies in an object accessing both the current item and its key

      Javascript

      $each( name John lang JS function(k v) alert( Key + k + Value + v ) )

      jQueryboxModel

      Deprecated in jQuery 13 (see jQuerysupport) States if the current page in the users browseris being rendered using the W3C CSS Box Model

      Added in version 10

      Example 1 Returns the box model for the if rame

      Javascript

      $(p)html(The box model for this iframe is ltspangt + jQueryboxModel + ltspangt)

      CSS

      p colorblue margin20px span colorred

      HTML

      ltpgt ltpgt

      Example 2 Returns false if the page is in Quirks Mode in Internet Explorer

      Javascript

      $boxModel

      Results

      false

      jQuerysupport

      A collect ion of propert ies that represent the presence of dif ferent browser features or bugs

      Added in version 13

      Rather than using $browser to detect the current user agent and alter the page presentat ionbased on which browser is running it is a good pract ice to perform feature detect ion Thismeans that prior to execut ing code which relies on a browser feature we test to ensure thatthe feature works properly To make this process simpler jQuery performs many such tests andmakes the results available to us as propert ies of the jQuerysupport object

      The values of all the support propert ies are determined using feature detect ion (and do notuse any form of browser snif f ing)

      Following are a few resources that explain how feature detection works

      httppetermichauxcaarticlesfeature-detection-state-of-the-art-browser-scripting

      httpwwwjibberingcomfaqfaq_notesnot_browser_detecthtml

      httpyurathinkweb2comcft

      While jQuery includes a number of propert ies developers should feel f ree to add their own as

      While jQuery includes a number of propert ies developers should feel f ree to add their own astheir needs dictate Many of the jQuerysupport propert ies are rather low-level so they aremost useful for plugin and jQuery core development rather than general day-to-daydevelopment Since jQuery requires these tests internally they must be performed on everypage load for that reason this list is kept short and limited to features needed by jQuery itself

      The tests included in jQuerysupport are as follows

      ajax is equal to t rue if a browser is able to create an XMLHttpRequest object

      boxModel is equal to t rue if the page is rendering according to the W3C CSS Box Model(is current ly false in IE 6 and 7 when they are in Quirks Mode) This property is null unt ildocument ready occurs

      changeBubbles is equal to t rue if the change event bubbles up the DOM tree asrequired by the W3C DOM event model (It is current ly false in IE and jQuery simulatesbubbling)

      checkClone is equal to t rue if a browser correct ly clones the checked state of radiobuttons or checkboxes in document f ragments

      checkOn is equal to t rue if the value of a checkbox defaults to on when no value isspecif ied

      cors is equal to t rue if a browser can create an XMLHttpRequest object and if thatXMLHttpRequest object has a withCredent ials property To enable cross-domainrequests in environments that do not support cors yet but do allow cross-domain XHRrequests (windows gadget etc) set $support cors = t rue CORS WD

      cssFloat is equal to t rue if the name of the property containing the CSS f loat value iscssFloat as def ined in the CSS Spec (It is current ly false in IE it uses styleFloat instead)

      hrefNormalized is equal to t rue if the getAttribute() method retrieves the href at t ributeof elements unchanged rather than normalizing it to a fully-qualif ied URL (It is current lyfalse in IE the URLs are normalized)

      htmlSerialize is equal to t rue if the browser is able to serializeinsert ltlinkgt elementsusing the innerHTML property of elements (is current ly false in IE)

      leadingWhitespace is equal to t rue if the browser inserts content with innerHTMLexact ly as providedacirceurordquospecif ically if leading whitespace characters are preserved (It iscurrent ly false in IE 6-8)

      noCloneChecked is equal to t rue if cloned DOM elements copy over the state of thechecked expando (It is current ly false in IE) (Added in jQuery 151)

      noCloneEvent is equal to t rue if cloned DOM elements are created without eventhandlers (that is if the event handlers on the source element are not cloned) (It iscurrent ly false in IE)

      opacity is equal to t rue if a browser can properly interpret the opacity style property (Itis current ly false in IE it uses alpha f ilters instead)

      optDisabled is equal to t rue if opt ion elements within disabled select elements are notautomat ically marked as disabled

      optSelected is equal to t rue if an ltopt iongt element that is selected by default has aworking selected property

      scriptEval() is equal to t rue if inline scripts are automat ically evaluated and executedwhen inserted into the document using standard DOM manipulat ion methods such asappendChild() and createTextNode() (It is current ly false in IE it uses text to insertexecutable scripts)

      Note No longer supported removed in jQuery 16 Prior to jQuery 151 the scriptEval()method was the stat ic scriptEval property The change to a method allowed the test tobe deferred unt il f irst use to prevent content security policy inline-script violat ions

      style is equal to t rue if inline styles for an element can be accessed through the DOMattribute called style as required by the DOM Level 2 specif icat ion In this casegetAttribute(style) can retrieve this value in Internet Explorer cssText is used for thispurpose

      submitBubbles is equal to t rue if the submit event bubbles up the DOM tree as requiredby the W3C DOM event model (It is current ly false in IE and jQuery simulates bubbling)

      tbody is equal to t rue if an empty lttablegt element can exist without a lttbodygt elementAccording to the HTML specif icat ion this sub-element is opt ional so the property shouldbe true in a fully-compliant browser If false we must account for the possibility of thebrowser inject ing lttbodygt tags implicit ly (It is current ly false in IE which automat icallyinserts tbody if it is not present in a string assigned to innerHTML)

      Example 1 Returns the box model for the if rame

      Javascript

      $(p)html(This frame uses the W3C box model ltspangt + jQuerysupportboxModel + ltspangt)

      CSS

      p colorblue margin20px span colorred

      HTML

      ltpgt ltpgt

      Example 2 Returns false if the page is in QuirksMode in Internet Explorer

      Javascript

      jQuerysupportboxModel

      Results

      false

      Plugin Authoring

      • JQuery Documentation
        • Core
          • jQueryholdReady
          • jQuerywhen
          • jQuerysub
          • jQuerynoConflict
          • jQuery
            • Selector Context
            • Using DOM elements
            • Cloning jQuery Objects
            • Returning an Empty Set
              • jQuery
                • Creating New Elements
                  • jQuery
                    • Selectors
                      • focus $(focus)
                      • selected $(selected)
                      • checked $(checked)
                      • disabled $(disabled)
                      • enabled $(enabled)
                      • file $(file)
                      • button $(button)
                      • reset $(reset)
                      • image $(image)
                      • submit $(submit)
                      • checkbox $(checkbox)
                      • radio $(radio)
                      • password $(password)
                      • text $(text)
                      • input $(input)
                      • only-child $(only-child)
                      • last-child $(last-child)
                      • first-child $(first-child)
                      • nth-child $(nth-child(indexevenoddequation))
                      • attributeContainsPrefix $([attribute|=value])
                      • attributeContainsWord $([attribute~=value])
                      • attributeMultiple $([attributeFilter1][attributeFilter2][attributeFilterN])
                      • attributeContains $([attribute=value])
                      • attributeEndsWith $([attribute$=value])
                      • attributeStartsWith $([attribute^=value])
                      • attributeNotEqual $([attribute=value])
                      • attributeEquals $([attribute=value])
                      • attributeHas $([attribute])
                      • visible $(visible)
                      • hidden $(hidden)
                      • parent $(parent)
                      • has $(has(selector))
                      • empty $(empty)
                      • contains $(contains(text))
                      • animated $(animated)
                      • header $(header)
                      • lt $(lt(index))
                      • gt $(gt(index))
                      • eq $(eq(index))
                      • odd $(odd)
                      • even $(even)
                      • not $(not(selector))
                      • Additional Notes
                      • last $(last)
                      • first $(first)
                      • next siblings $(prev ~ siblings)
                      • next adjacent $(prev + next)
                      • child $(parent gt child)
                      • descendant $(ancestor descendant)
                      • multiple $(selector1 selector2 selectorN)
                      • all $()
                      • class $(class)
                      • element $(element)
                      • id $(id)
                        • Traversing
                          • has
                          • parentsUntil
                          • prevUntil
                          • nextUntil
                          • each
                          • first
                          • last
                          • slice
                            • Negative Indices
                              • end
                              • andSelf
                              • siblings
                              • prevAll
                              • prev
                              • parents
                              • parent
                              • offsetParent
                              • nextAll
                              • next
                              • find
                              • contents
                              • closest
                              • closest
                              • children
                              • add
                              • not
                                • Removing Specific Elements
                                  • map
                                  • is
                                    • Using a Function
                                      • eq
                                      • filter
                                        • Using a Filter Function
                                            • Attributes
                                              • removeProp
                                              • prop
                                              • prop
                                                • Computed property values
                                                  • val
                                                  • val
                                                  • html
                                                  • html
                                                  • toggleClass
                                                  • removeClass
                                                  • hasClass
                                                  • removeAttr
                                                  • attr
                                                  • attr
                                                    • Setting a simple attribute
                                                    • Setting several attributes at once
                                                    • Computed attribute values
                                                      • addClass
                                                        • CSS
                                                          • jQuerycssHooks
                                                            • Feature Testing
                                                            • Defining a complete cssHook
                                                            • Special units
                                                            • Animating with cssHooks
                                                              • outerWidth
                                                              • outerHeight
                                                              • innerWidth
                                                              • innerHeight
                                                              • width
                                                              • width
                                                              • height
                                                              • height
                                                              • scrollLeft
                                                              • scrollLeft
                                                              • scrollTop
                                                              • scrollTop
                                                              • position
                                                              • offset
                                                              • offset
                                                              • css
                                                              • css
                                                              • toggleClass see Attributes
                                                              • removeClass see Attributes
                                                              • hasClass see Attributes
                                                              • addClass see Attributes
                                                                • Manipulation
                                                                  • removeProp see Attributes
                                                                  • prop see Attributes
                                                                  • prop see Attributes
                                                                  • outerWidth see CSS
                                                                  • outerHeight see CSS
                                                                  • innerWidth see CSS
                                                                  • innerHeight see CSS
                                                                  • width see CSS
                                                                  • width see CSS
                                                                  • height see CSS
                                                                  • height see CSS
                                                                  • scrollLeft see CSS
                                                                  • scrollLeft see CSS
                                                                  • scrollTop see CSS
                                                                  • scrollTop see CSS
                                                                  • position see CSS
                                                                  • offset see CSS
                                                                  • offset see CSS
                                                                  • css see CSS
                                                                  • css see CSS
                                                                  • unwrap
                                                                  • detach
                                                                  • clone
                                                                  • remove
                                                                  • empty
                                                                  • replaceAll
                                                                  • replaceWith
                                                                  • wrapInner
                                                                  • wrapAll
                                                                  • wrap
                                                                  • insertBefore
                                                                  • before
                                                                    • Additional Arguments
                                                                      • insertAfter
                                                                      • after
                                                                        • Inserting Disconnected DOM nodes
                                                                        • Passing a Function
                                                                        • Additional Arguments
                                                                          • prependTo
                                                                          • prepend
                                                                            • Additional Arguments
                                                                              • appendTo
                                                                              • append
                                                                                • Additional Arguments
                                                                                  • val see Attributes
                                                                                  • val see Attributes
                                                                                  • text
                                                                                  • text
                                                                                  • html see Attributes
                                                                                  • html see Attributes
                                                                                  • toggleClass see Attributes
                                                                                  • removeClass see Attributes
                                                                                  • hasClass see Attributes
                                                                                  • removeAttr see Attributes
                                                                                  • attr see Attributes
                                                                                  • attr see Attributes
                                                                                  • addClass see Attributes
                                                                                    • Data
                                                                                      • jQueryhasData
                                                                                      • jQueryremoveData
                                                                                      • jQuerydata
                                                                                      • jQuerydata
                                                                                      • jQuerydequeue
                                                                                      • jQueryqueue
                                                                                      • jQueryqueue
                                                                                      • clearQueue
                                                                                      • removeData
                                                                                      • data
                                                                                      • data
                                                                                      • dequeue
                                                                                      • queue
                                                                                      • queue
                                                                                        • Forms
                                                                                          • submit
                                                                                          • select
                                                                                          • change
                                                                                          • blur
                                                                                          • focus
                                                                                          • serializeArray
                                                                                          • serialize
                                                                                          • jQueryparam
                                                                                          • val see Attributes
                                                                                          • val see Attributes
                                                                                            • Events
                                                                                              • toggle
                                                                                              • eventnamespace
                                                                                              • undelegate
                                                                                              • delegate
                                                                                              • jQueryproxy
                                                                                              • focusout
                                                                                              • focusin
                                                                                              • eventisImmediatePropagationStopped
                                                                                              • eventstopImmediatePropagation
                                                                                              • eventisPropagationStopped
                                                                                              • eventstopPropagation
                                                                                              • eventisDefaultPrevented
                                                                                              • eventpreventDefault
                                                                                              • eventtimeStamp
                                                                                              • eventresult
                                                                                              • eventwhich
                                                                                              • eventpageY
                                                                                              • eventpageX
                                                                                              • eventcurrentTarget
                                                                                              • eventrelatedTarget
                                                                                              • eventdata
                                                                                              • eventtarget
                                                                                              • eventtype
                                                                                              • keydown
                                                                                              • scroll
                                                                                              • resize
                                                                                              • keyup
                                                                                              • keypress
                                                                                              • submit see Forms
                                                                                              • select see Forms
                                                                                              • change see Forms
                                                                                              • blur see Forms
                                                                                              • focus see Forms
                                                                                              • mousemove
                                                                                              • hover
                                                                                              • hover
                                                                                              • mouseleave
                                                                                              • mouseenter
                                                                                              • mouseout
                                                                                              • mouseover
                                                                                              • dblclick
                                                                                              • click
                                                                                              • mouseup
                                                                                              • mousedown
                                                                                              • error
                                                                                              • unload
                                                                                              • load
                                                                                              • ready
                                                                                                • Aliasing the jQuery Namespace
                                                                                                  • die
                                                                                                  • die
                                                                                                  • live
                                                                                                    • Event Delegation
                                                                                                    • Multiple Events
                                                                                                    • Event Data
                                                                                                    • Event Context
                                                                                                    • Caveats
                                                                                                      • triggerHandler
                                                                                                      • trigger
                                                                                                      • one
                                                                                                      • unbind
                                                                                                        • Using Namespaces
                                                                                                        • Using the Event Object
                                                                                                          • bind
                                                                                                            • Multiple Events
                                                                                                            • Event Handlers
                                                                                                            • The Event object
                                                                                                            • Passing Event Data
                                                                                                                • Deferred Object
                                                                                                                  • deferredpipe
                                                                                                                  • deferredalways
                                                                                                                  • promise
                                                                                                                  • deferredpromise
                                                                                                                  • jQuerywhen see Core
                                                                                                                  • deferredresolveWith
                                                                                                                  • deferredrejectWith
                                                                                                                  • deferredfail
                                                                                                                  • deferreddone
                                                                                                                  • deferredthen
                                                                                                                  • deferredreject
                                                                                                                  • deferredisRejected
                                                                                                                  • deferredisResolved
                                                                                                                  • deferredresolve
                                                                                                                    • Effects
                                                                                                                      • fadeToggle
                                                                                                                        • Easing
                                                                                                                        • Callback Function
                                                                                                                          • jQueryfxinterval
                                                                                                                          • delay
                                                                                                                          • jQueryfxoff
                                                                                                                          • clearQueue see Data
                                                                                                                          • dequeue see Data
                                                                                                                          • queue see Data
                                                                                                                          • queue see Data
                                                                                                                          • stop
                                                                                                                          • animate
                                                                                                                            • Animation Properties and Values
                                                                                                                            • Duration
                                                                                                                            • Complete Function
                                                                                                                            • Basic Usage
                                                                                                                            • Step Function
                                                                                                                            • Easing
                                                                                                                            • Per-property Easing
                                                                                                                              • fadeTo
                                                                                                                              • fadeOut
                                                                                                                                • Easing
                                                                                                                                • Callback Function
                                                                                                                                  • fadeIn
                                                                                                                                    • Easing
                                                                                                                                    • Callback Function
                                                                                                                                      • slideToggle
                                                                                                                                        • Easing
                                                                                                                                        • Callback Function
                                                                                                                                          • slideUp
                                                                                                                                            • Easing
                                                                                                                                            • Callback Function
                                                                                                                                              • slideDown
                                                                                                                                                • Easing
                                                                                                                                                • Callback Function
                                                                                                                                                  • toggle
                                                                                                                                                  • hide
                                                                                                                                                  • show
                                                                                                                                                    • Ajax
                                                                                                                                                      • jQueryajaxPrefilter
                                                                                                                                                      • ajaxComplete
                                                                                                                                                      • serializeArray see Forms
                                                                                                                                                      • serialize see Forms
                                                                                                                                                      • jQueryajaxSetup
                                                                                                                                                      • ajaxSuccess
                                                                                                                                                      • ajaxStop
                                                                                                                                                      • ajaxStart
                                                                                                                                                      • ajaxSend
                                                                                                                                                      • ajaxError
                                                                                                                                                      • jQuerypost
                                                                                                                                                        • The jqXHR Object
                                                                                                                                                          • jQuerygetScript
                                                                                                                                                          • jQuerygetJSON
                                                                                                                                                            • JSONP
                                                                                                                                                            • The jqXHR Object
                                                                                                                                                              • jQueryget
                                                                                                                                                                • The jqXHR Object
                                                                                                                                                                  • load
                                                                                                                                                                    • Loading Page Fragments
                                                                                                                                                                      • jQueryajax
                                                                                                                                                                        • The jqXHR Object
                                                                                                                                                                        • Callback Function Queues
                                                                                                                                                                        • Data Types
                                                                                                                                                                        • Sending Data to the Server
                                                                                                                                                                        • Advanced Options
                                                                                                                                                                        • Extending Ajax
                                                                                                                                                                          • jQueryparam see Forms
                                                                                                                                                                            • Miscellaneous
                                                                                                                                                                              • each see Traversing
                                                                                                                                                                              • toArray
                                                                                                                                                                              • index
                                                                                                                                                                                • Return Values
                                                                                                                                                                                • Detail
                                                                                                                                                                                  • removeData see Data
                                                                                                                                                                                  • data see Data
                                                                                                                                                                                  • data see Data
                                                                                                                                                                                  • get
                                                                                                                                                                                  • size
                                                                                                                                                                                  • jQuerynoConflict see Core
                                                                                                                                                                                  • jQueryparam see Forms
                                                                                                                                                                                    • Dimensions
                                                                                                                                                                                      • outerWidth see CSS
                                                                                                                                                                                      • outerHeight see CSS
                                                                                                                                                                                      • innerWidth see CSS
                                                                                                                                                                                      • innerHeight see CSS
                                                                                                                                                                                      • width see CSS
                                                                                                                                                                                      • width see CSS
                                                                                                                                                                                      • height see CSS
                                                                                                                                                                                      • height see CSS
                                                                                                                                                                                        • Offset
                                                                                                                                                                                          • offsetParent see Traversing
                                                                                                                                                                                          • scrollLeft see CSS
                                                                                                                                                                                          • scrollLeft see CSS
                                                                                                                                                                                          • scrollTop see CSS
                                                                                                                                                                                          • scrollTop see CSS
                                                                                                                                                                                          • position see CSS
                                                                                                                                                                                          • offset see CSS
                                                                                                                                                                                          • offset see CSS
                                                                                                                                                                                            • Utilities
                                                                                                                                                                                              • jQuerynow
                                                                                                                                                                                              • jQueryparseXML
                                                                                                                                                                                              • jQuerytype
                                                                                                                                                                                              • jQueryisWindow
                                                                                                                                                                                              • jQueryparseJSON
                                                                                                                                                                                              • jQueryproxy see Events
                                                                                                                                                                                              • jQuerycontains
                                                                                                                                                                                              • jQuerynoop
                                                                                                                                                                                              • jQueryglobalEval
                                                                                                                                                                                              • jQueryisXMLDoc
                                                                                                                                                                                              • jQueryremoveData see Data
                                                                                                                                                                                              • jQuerydata see Data
                                                                                                                                                                                              • jQuerydata see Data
                                                                                                                                                                                              • jQuerydequeue see Data
                                                                                                                                                                                              • jQueryqueue see Data
                                                                                                                                                                                              • jQueryqueue see Data
                                                                                                                                                                                              • clearQueue see Data
                                                                                                                                                                                              • jQueryisEmptyObject
                                                                                                                                                                                              • jQueryisPlainObject
                                                                                                                                                                                              • dequeue see Data
                                                                                                                                                                                              • queue see Data
                                                                                                                                                                                              • queue see Data
                                                                                                                                                                                              • jQuerybrowser
                                                                                                                                                                                              • jQuerybrowserversion
                                                                                                                                                                                              • jQuerytrim
                                                                                                                                                                                              • jQueryisFunction
                                                                                                                                                                                              • jQueryisArray
                                                                                                                                                                                              • jQueryunique
                                                                                                                                                                                              • jQuerymerge
                                                                                                                                                                                              • jQueryinArray
                                                                                                                                                                                              • jQuerymap
                                                                                                                                                                                              • jQuerymakeArray
                                                                                                                                                                                              • jQuerygrep
                                                                                                                                                                                              • jQueryextend
                                                                                                                                                                                              • jQueryeach
                                                                                                                                                                                              • jQueryboxModel
                                                                                                                                                                                              • jQuerysupport
                                                                                                                                                                                                • Plugin Authoring

        (function() var sub$ = jQuerysub()

        sub$fnmyCustomMethod = function() return just for me

        sub$(document)ready(function() sub$(body)myCustomMethod() just for me ) )() typeof jQuery(body)myCustomMethod undefined

        Example 2 Override some jQuery methods to provide new funct ionality

        Javascript

        (function() var myjQuery = jQuerysub()

        myjQueryfnremove = function() New functionality Trigger a remove event thistrigger(remove)

        Be sure to call the original jQuery remove method return jQueryfnremoveapply( this arguments )

        myjQuery(function($) $(menu)cl ick(function() $(this)find(submenu)remove() )

        A new remove event is now triggered from this copy of jQuery $(document)bind(remove function(e) $(etarget)parent()hide() ) ))()

        Regular jQuery doesnt trigger a remove event when removing an element This functionality is only contained within the modified myjQuery

        Example 3 Create a plugin that returns plugin-specif ic methods

        Javascript

        (function() Create a new copy of jQuery using sub() var plugin = jQuerysub()

        Extend that copy with the new plugin methods pluginfnextend( open function() return thisshow() close function() return thishide() )

        Add our plugin to the original jQuery jQueryfnmyplugin = function() thisaddClass(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 Call ing just $(main)open() wont work as open doesnt exist)

        jQuerynoConflict

        Relinquish jQuerys control of the $ variable

        Added in version 10

        jQuerynoConf lict (removeAll)Object

        removeAllBoolean (opt ional) A Boolean indicat ing whether to remove all jQueryvariables f rom the global scope (including jQuery itself )

        Many JavaScript libraries use $ as a funct ion or variable name just as jQuery does In jQueryscase $ is just an alias for jQuery so all funct ionality is available without using $ If we need touse another JavaScript library alongside jQuery we can return control of $ back to the otherlibrary with a call to $noConf lict ()

        ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() Code that uses other l ibrarys $ can follow hereltscriptgt

        This technique is especially ef fect ive in conjunct ion with the ready() methods ability to aliasthe jQuery object as within callback passed to ready() we can use $ if we wish without fear ofconf licts later

        ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() jQuery(document)ready(function($) Code that uses jQuerys $ can follow here ) Code that uses other l ibrarys $ can follow hereltscriptgt

        If necessary we can free up the jQuery name as well by passing true as an argument to themethod This is rarely necessary and if we must do this (for example if we need to use mult ipleversions of the jQuery library on the same page) we need to consider that most plug-ins relyon the presence of the jQuery variable and may not operate correct ly in this situat ion

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

        Javascript

        jQuerynoConfl ict() Do something with jQueryjQuery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

        Example 2 Reverts the $ alias and then creates and executes a funct ion to provide the $ as ajQuery alias inside the funct ions scope Inside the funct ion the original $ object is not availableThis works well for most plugins that dont rely on any other library

        Javascript

        jQuerynoConfl ict()(function($) $(function() more code using $ as alias to jQuery ))(jQuery) other code using $ as an alias to the other l ibrary

        Example 3 You can chain the jQuerynoConf lict () with the shorthand ready for a compact code

        Javascript

        jQuerynoConfl ict()(function() code using jQuery) other code using $ as an alias to the other l ibrary

        Example 4 Creates a dif ferent alias instead of jQuery to use in the rest of the script

        Javascript

        var j = jQuerynoConfl ict() Do something with jQueryj(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none

        Example 5 Completely move jQuery to a new namespace in another object

        Javascript

        var dom = domquery = jQuerynoConfl ict(true)

        Results

        Do something with the new jQuerydomquery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none Do something with another version of jQueryjQuery(div gt p)hide()

        jQuery

        Accepts a string containing a CSS selector which is then used to match a set of elements

        Added in version 14

        jQuery()jQuery

        In the f irst formulat ion listed above jQuery() acirceurordquo which can also be writ ten as $() acirceurordquo searchesthrough the DOM for any elements that match the provided selector and creates a new jQueryobject that references these elements

        $(divfoo)

        Selector Context

        By default selectors perform their searches within the DOM start ing at the document rootHowever an alternate context can be given for the search by using the opt ional secondparameter to the $() funct ion For example to do a search within an event handler the searchcan be restricted like so

        $(divfoo)cl ick(function() $(span this)addClass(bar))

        When the search for the span selector is restricted to the context of this only spans within theclicked element will get the addit ional class

        Internally selector context is implemented with the f ind() method so $(span this) is equivalentto $(this)f ind(span)

        Using DOM elements

        The second and third formulat ions of this funct ion create a jQuery object using one or moreDOM elements that were already selected in some other way A common use of this facility isto call jQuery methods on an element that has been passed to a callback funct ion through thekeyword this

        $(divfoo)cl ick(function() $(this)sl ideUp())

        This example causes elements to be hidden with a sliding animat ion when clicked Because thehandler receives the clicked item in the this keyword as a bare DOM element the element mustbe passed to the $() funct ion before applying jQuery methods to it

        XML data returned from an Ajax call can be passed to the $() funct ion so individual elements of

        the XML structure can be retrieved using f ind() and other DOM traversal methods

        $post(urlxml function(data) var $child = $(data)find(child))

        Cloning jQuery Objects

        When a jQuery object is passed to the $() funct ion a clone of the object is created This newjQuery object references the same DOM elements as the init ial one

        Returning an Empty Set

        As of jQuery 14 calling the jQuery() method with no arguments returns an empty jQuery set(with a length property of 0) In previous versions of jQuery this would return a set containingthe document node

        Example 1 Find all p elements that are children of a div element and apply a border to them

        Javascript

        $(div gt p)css(border 1px solid gray)

        HTML

        ltpgtoneltpgt ltdivgtltpgttwoltpgtltdivgt ltpgtthreeltpgt

        Example 2 Find all inputs of type radio within the f irst form in the document

        Javascript

        $(inputradio documentforms[0])

        Example 3 Find all div elements within an XML document f rom an Ajax response

        Javascript

        $(div xmlresponseXML)

        Example 4 Set the background color of the page to black

        Javascript

        $(documentbody)css( background black )

        Example 5 Hide all the input elements within a form

        Javascript

        $(myFormelements)hide()

        jQuery

        Creates DOM elements on the f ly f rom the provided string of raw HTML

        Added in version 14

        jQuery(html props)jQuery

        htmlString A string def ining a single standalone HTML element (eg ltdivgt orltdivgtltdivgt)

        propsObject An map of at t ributes events and methods to call on the newly-createdelement

        Creating New Elements

        If a string is passed as the parameter to $() jQuery examines the string to see if it looks likeHTML (ie it has lttag gt somewhere within the string) If not the string is interpreted as aselector expression as explained above But if the string appears to be an HTML snippetjQuery at tempts to create new DOM elements as described by the HTML Then a jQuery objectis created and returned that refers to these elements You can perform any of the usual jQuerymethods on this object

        $(ltp id=testgtMy ltemgtnewltemgt textltpgt)appendTo(body)

        If the HTML is more complex than a single tag without at t ributes as it is in the above examplethe actual creat ion of the elements is handled by the browsers innerHTML mechanism In mostcases jQuery creates a new

        element and sets the innerHTML property of the element to the HTML snippet that was passedin When the parameter has a single tag such as$(ltimgAcirc gt) or $(ltagtltagt) jQuery creates the element using the nat ive JavaScriptcreateElement() funct ion

        When passing in complex HTML some browsers may not generate a DOM that exact ly

        replicates the HTML source provided As ment ioned we use the browsers innerHTML propertyto parse the passed HTML and insert it into the current document During this process somebrowsers f ilter out certain elements such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements inserted may not be representat ive of the original string passed

        Filtering isnt however just limited to these tags For example Internet Explorer prior to version 8will also convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

        To ensure cross-plat form compat ibility the snippet must be well-formed Tags that can containother elements should be paired with a closing tag

        $(lta href=httpjquerycomgtltagt)

        Alternat ively jQuery allows XML-like tag syntax (with or without a space before the slash)

        $(ltagt)

        Tags that cannot contain elements may be quick-closed or not

        $(ltimg gt)$(ltinputgt)

        When passing HTML to jQuery() please also note that text nodes are not t reated as DOMelements With the except ion of a few methods (such as content()) they are generallyotherwise ignored or removed Eg

        var el = $(1ltbrgt2ltbrgt3) returns [ltbrgt 2 ltbrgt] el = $(1ltbrgt2ltbrgt3 gt) returns [ltbrgt 2 ltbrgt 3 ampgt]

        This behaviour is expected

        As of jQuery 14 the second argument to jQuery() can accept a map consist ing of a supersetof the propert ies that can be passed to the at t r() method Furthermore any event type can bepassed in and the following jQuery methods can be called val css html text data widthheight or of fset The name class must be quoted in the map since it is a JavaScript reservedword and className cannot be used since it is not the correct at t ribute name

        Note Internet Explorer will not allow you to create an input or button element and change itstype you must specify the type using ltinput type=checkbox gt for example A demonstrat ionof this can be seen below

        Unsupported in IE

        $(ltinput gt type text name test)appendTo(body)

        Supported workaround

        $(ltinput type=text gt)attr( name test)appendTo(body)

        Example 1 Create a div element (and all of its contents) dynamically and append it to the bodyelement Internally an element is created and its innerHTML property set to the given markup

        Javascript

        $(ltdivgtltpgtHelloltpgtltdivgt)appendTo(body)

        Example 2 Create some DOM elements

        Javascript

        $(ltdivgt class test text Click me cl ick function() $(this)toggleClass(test) )appendTo(body)

        jQuery

        Binds a funct ion to be executed when the DOM has f inished loading

        Added in version 10

        jQuery(callback)jQuery

        callbackFunct ion The funct ion to execute when the DOM is ready

        This funct ion behaves just like $(document)ready() in that it should be used to wrap other $()operat ions on your page that depend on the DOM being ready While this funct ion is

        technically chainable there really isnt much use for chaining against it

        Example 1 Execute the funct ion when the DOM is ready to be used

        Javascript

        $(function() Document is ready )

        Example 2 Use both the shortcut for $(document)ready() and the argument to write failsafejQuery code using the $ alias without relying on the global alias

        Javascript

        jQuery(function($) Your code using failsafe $ alias here )

        Selectors

        focus $(focus)

        Selects element if it is current ly focused

        Added in version 16

        $(focus)

        As with other pseudo-class selectors (those that begin with a ) it is recommended toprecede focus with a tag name or some other selector otherwise the universal selector () isimplied In other words the bare $(focus) is equivalent to $(focus) If you are looking for thecurrent ly focused element $( documentact iveElement ) will retrieve it without having to searchthe whole DOM tree

        Example 1 Adds the focused class to whatever element has focus

        Javascript

        $()l ive(focus blur function(e) var el = $(this) setTimeout(function() eltoggleClass(focused elis(focus)) 0))

        CSS

        focused background abcdef

        HTML

        ltinput tabIndex=1gtltinput tabIndex=2gtltselect tabIndex=3gt ltoptiongtselect menultoptiongtltselectgtltdiv tabIndex=4gt a divltdivgt

        selected $(selected)

        Selects all elements that are selected

        Added in version 10

        $(selected)

        The selected selector works for ltopt iongt elements It does not work for checkboxes or radioinputs use checked for them

        Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

        Javascript

        $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) trigger(change)

        CSS

        div colorred

        HTML

        ltselect name=garden multiple=multiplegt

        ltoptiongtFlowersltoptiongt ltoption selected=selectedgtShrubsltoptiongt ltoptiongtTreesltoptiongt ltoption selected=selectedgtBushesltoptiongt

        ltoptiongtGrassltoptiongt ltoptiongtDirtltoptiongt ltselectgt ltdivgtltdivgt

        checked $(checked)

        Matches all elements that are checked

        Added in version 10

        $(checked)

        The checked selector works for checkboxes and radio buttons For select elements use theselected selector

        Example 1 Finds all input elements that are checked

        Javascript

        function countChecked() var n = $(inputchecked)length $(div)text(n + (n lt= 1 is are) + checked)countChecked()$(checkbox)cl ick(countChecked)

        CSS

        div colorred

        HTML

        ltformgt ltpgt ltinput type=checkbox name=newsletter checked=checked value=Hourly gt

        ltinput type=checkbox name=newsletter value=Daily gt ltinput type=checkbox name=newsletter value=Weekly gt

        ltinput type=checkbox name=newsletter checked=checked value=Monthly gt ltinput type=checkbox name=newsletter value=Yearly gt ltpgtltformgtltdivgtltdivgt

        Example 2

        Javascript

        $(input)cl ick(function() $(log)html( $(checked)val() + is checked ))

        CSS

        input label l ine-height 15em

        HTML

        ltformgt ltdivgt ltinput type=radio name=fruit value=orange id=orangegt ltlabel for=orangegtorangeltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=apple id=applegt ltlabel for=applegtappleltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=banana id=bananagt ltlabel for=bananagtbananaltlabelgt ltdivgt ltdiv id=loggtltdivgtltformgt

        disabled $(disabled)

        Selects all elements that are disabled

        Added in version 10

        $(disabled)

        As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(disabled) is equivalent to $(disabled) so $(inputdisabled) should beused instead

        Example 1 Finds all input elements that are disabled

        Javascript

        $(inputdisabled)val(this is it)

        HTML

        ltformgt

        ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

        enabled $(enabled)

        Selects all elements that are enabled

        Added in version 10

        $(enabled)

        As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(enabled) is equivalent to $(enabled) so $(inputenabled) should beused instead

        Example 1 Finds all input elements that are enabled

        Javascript

        $(inputenabled)val(this is it)

        HTML

        ltformgt

        ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt

        file $(file)

        Selects all elements of type f ile

        Added in version 10

        $(f ile)

        f ile is equivalent to [type=f ile] 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 theuniversal selector () is implied In other words the bare $(f ile) is equivalent to $(f ile) so$(inputf ile) should be used instead

        Example 1 Finds all f ile inputs

        Javascript

        var input = $(inputfi le)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height45px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        button $(button)

        Selects all but ton elements and elements of type button

        Added in version 10

        $(button)

        Example 1 Finds all but ton inputs

        Javascript

        var input = $(button)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height45px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        reset $(reset)

        Selects all elements of type reset

        Added in version 10

        $(reset)

        reset is equivalent to [type=reset]

        Example 1 Finds all reset inputs

        Javascript

        var input = $(inputreset)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height45px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        image $(image)

        Selects all elements of type image

        Added in version 10

        $(image)

        image is equivalent to [type=image]

        Example 1 Finds all image inputs

        Javascript

        var input = $(inputimage)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height45px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        submit $(submit)

        Selects all elements of type submit

        Added in version 10

        $(submit)

        The submit selector typically applies to button or input elements Note that some browserstreat ltbuttongt element as type=default implicit ly while others (such as Internet Explorer) donot

        Example 1 Finds all submit elements that are descendants of a td element

        Javascript

        var submitEl = $(td submit) parent(td) css(backgroundyellow border3px red solid) end() $(result)text( jQuery matched + submitEllength + elements)

        so it wont 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 = inputElattr(type) type= + inputElattr(type) + $(el)before(lttdgt + inputEl[0]nodeName + inputType + lttdgt) )

        CSS

        textarea height45px

        HTML

        lttablegtltformgtlttable id=exampleTable border=1 cellpadding=10 align=centergt

        lttrgt ltthgt Element Type ltthgt ltthgt Element ltthgt

        lttr lttrgt lttdgt ltinput type=button value=Input Buttongt lttdgt

        lttrgt lttrgt lttdgt ltinput type=checkbox gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=fi le gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=hidden gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=image gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=password gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=radio gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=reset gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=submit gt lttdgt

        lttrgt lttrgt lttdgt ltinput type=text gt lttdgt

        lttrgt lttrgt lttdgt ltselectgtltoptiongtOptionltoptiongtltselectgt lttdgt

        lttrgt lttrgt lttdgt lttextareagtlttextareagt lttdgt lttrgt

        lttrgt lttdgt ltbuttongtButtonltbuttongt lttdgt lttrgt lttrgt lttdgt ltbutton type=submitgtButton type=submitltbuttongt lttdgt lttrgt

        lttablegtltformgtltdiv id=resultgtltdivgt

        checkbox $(checkbox)

        Selects all elements of type checkbox

        Added in version 10

        $(checkbox)

        $(checkbox) is equivalent to $([type=checkbox]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(checkbox) isequivalent to $(checkbox) so $(inputcheckbox) should be used instead

        Example 1 Finds all checkbox inputs

        Javascript

        var input = $(form inputcheckbox)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height25px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=checkbox gt ltinput type=fi le gt ltinput type=hidden gt

        ltinput type=image gt ltinput type=password gt ltinput type=radio gt

        ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

        ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

        ltdivgt ltdivgt

        radio $(radio)

        Selects all elements of type radio

        Added in version 10

        $(radio)

        $(radio) is equivalent to $([type=radio]) As with other pseudo-class selectors (those thatbegin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(radio) is equivalentto $(radio) so $(inputradio) should be used instead

        To select a set of associated radio buttons you might use $(input[name=gender]radio)

        Example 1 Finds all radio inputs

        Javascript

        var input = $(form inputradio)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height25px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio name=asdf gt ltinput type=radio name=asdf gt

        ltinput type=reset gt ltinput type=submit gt ltinput type=text gt

        ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt

        ltdivgt ltdivgt

        password $(password)

        Selects all elements of type password

        Added in version 10

        $(password)

        $(password) is equivalent to $([type=password]) As with other pseudo-class selectors (thosethat 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 $(password) isequivalent to $(password) so $(inputpassword) should be used instead

        Example 1 Finds all password inputs

        Javascript

        var input = $(inputpassword)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height45px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        text $(text)

        Selects all elements of type text

        Added in version 10

        $(text)

        $(text ) is equivalent to $([type=text ]) and thus selects all ltinput type=textgt elements Aswith other pseudo-class selectors (those that begin with a ) it is recommended to precede itwith a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(text ) is equivalent to $(text ) so $(inputtext ) should be usedinstead

        Note As of jQuery 152 text selects input elements that have no specif ied type at t ribute (inwhich case type=text is implied)

        Example 1 Finds all text inputs

        Javascript

        var input = $(form inputtext)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit

        CSS

        textarea height25px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt

        input $(input)

        Selects all input textarea select and button elements

        Added in version 10

        $(input)

        The input selector basically selects all form controls

        Example 1 Finds all input elements

        Javascript

        var all Inputs = $(input) var formChildren = $(form gt ) $(messages)text(Found + all Inputslength + inputs and the form has + formChildrenlength + children) so it wont submit $(form)submit(function () return false )

        CSS

        textarea height25px

        HTML

        ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt

        ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt

        ltinput type=password gt ltinput type=radio gt ltinput type=reset gt

        ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt

        lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdiv id=messagesgt ltdivgt

        only-child $(only-child)

        Selects all elements that are the only child of their parent

        Added in version 114

        $(only-child)

        If the parent has other child elements nothing is matched

        Example 1 Change the text and add a border for each button that is the only child of its parent

        Javascript

        $(div buttononly-child)text(Alone)css(border 2px blue solid)

        CSS

        div width100px height80px margin5px floatleft backgroundb9e

        HTML

        ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongtltdivgt

        ltdivgt ltbuttongtSiblingltbuttongtltdivgtltdivgt Noneltdivgt

        ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt

        ltdivgtltdivgt ltbuttongtSiblingltbuttongtltdivgt

        last-child $(last-child)

        Selects all elements that are the last child of their parent

        Added in version 114

        $(last-child)

        While last matches only a single element last-child can match more than one one for eachparent

        Example 1 Finds the last span in each matched div and adds some css plus a hover state

        Javascript

        $(div spanlast-child) css(colorred fontSize80) hover(function () $(this)addClass(solast) function () $(this)removeClass(solast) )

        CSS

        spansolast text-decorationl ine-through

        HTML

        ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

        ltspangtSamltspangt ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt

        ltspangtRalphltspangt ltspangtDavidltspangt ltdivgt

        first-child $(first-child)

        Selects all elements that are the f irst child of their parent

        Added in version 114

        $(f irst-child)

        While f irst matches only a single element the f irst-child selector can match more than oneone for each parent This is equivalent to nth-child(1)

        Example 1 Finds the f irst span in each matched div to underline and add a hover state

        Javascript

        $(div spanfirst-child) css(text-decoration underline) hover(function () $(this)addClass(sogreen) function () $(this)removeClass(sogreen) )

        CSS

        span color008 spansogreen colorgreen font-weight bolder

        HTML

        ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt

        ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt ltspangtRalphltspangt

        ltdivgt

        nth-child $(nth-child(indexevenoddequation))

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

        Added in version 114

        $(nth-child(indexevenoddequat ion))

        indexNumberString The index of each child to match start ing with 1 the string evenor odd or an equat ion ( eg nth-child(even) nth-child(4n) )

        Because jQuerys implementat ion of nth-child(n) is strict ly derived from the CSS specif icat ionthe value of n is 1-indexed meaning that the count ing starts at 1 For all other selectorexpressions however jQuery follows JavaScript s 0-indexed count ing Therefore given asingle ltulgt containing two ltligts $(linth-child(1)) selects the f irst ltligt while $(lieq(1)) selectsthe second

        The nth-child(n) pseudo-class is easily confused with eq(n) even though the two can result indramat ically dif ferent matched elements With nth-child(n) all children are counted regardlessof what they are and the specif ied element is selected only if it matches the selector at tachedto the pseudo-class With eq(n) only the selector at tached to the pseudo-class is counted notlimited 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 W3C CSS specif icat ion

        Example 1 Finds the second li in each matched ul and notes it

        Javascript

        $(ul l i nth-child(2))append(ltspangt - 2ndltspangt)

        CSS

        div floatleft span colorblue

        HTML

        ltdivgtltulgt ltligtJohnltligt ltligtKarlltl igt ltligtBrandonltligt

        ltulgtltdivgt ltdivgtltulgt ltligtSamltligt ltulgtltdivgt

        ltdivgtltulgt ltligtGlenltligt ltligtTaneltligt ltligtRalphltligt

        ltligtDavidltligt ltulgtltdivgt

        Example 2 This is a playground to see how the selector works with dif ferent strings Not icethat this is dif ferent f rom the even and odd which have no regard for parent and just f ilter thelist of elements to every other one The nth-child however counts the index of the child to itspart icular parent In any case it s easier to see than explain so

        Javascript

        $(button)cl ick(function () var str = $(this)text() $(tr)css(background white) $(tr + str)css(background ff0000) $(inner)text(str) )

        CSS

        button displayblock font-size12px width100px div floatleft margin10px font-size10px border1px solid black span colorblue font-size18px inner colorred td width50px text-aligncenter

        HTML

        ltdivgt ltbuttongtnth-child(even)ltbuttongt ltbuttongtnth-child(odd)ltbuttongt ltbuttongtnth-child(3n)ltbuttongt

        ltbuttongtnth-child(2)ltbuttongt ltdivgt ltdivgt ltbuttongtnth-child(3n+1)ltbuttongt ltbuttongtnth-child(3n+2)ltbuttongt

        ltbuttongtevenltbuttongt ltbuttongtoddltbuttongt ltdivgt ltdivgtlttablegt

        lttrgtlttdgtJohnlttdgtlttrgt lttrgtlttdgtKarllttdgtlttrgt lttrgtlttdgtBrandonlttdgtlttrgt

        lttrgtlttdgtBenjaminlttdgtlttrgt lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtSamlttdgtlttrgt

        lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtGlenlttdgtlttrgt lttrgtlttdgtTanelttdgtlttrgt

        lttrgtlttdgtRalphlttdgtlttrgt lttrgtlttdgtDavidlttdgtlttrgt lttrgtlttdgtMikelttdgtlttrgt

        lttrgtlttdgtDanlttdgtlttrgt lttablegtltdivgt ltspangt trltspan id=innergtltspangt

        ltspangt

        attributeContainsPrefix $([attribute|=value])

        Selects elements that have the specif ied at t ribute with a value either equal to a given string orstart ing with that string followed by a hyphen (-)

        Added in version 10

        $([at t ribute|=value])

        attributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        This selector was introduced into the CSS specif icat ion to handle language at t ributes

        Example 1 Finds all links with an href lang at t ribute that is english

        Javascript

        $(a[hreflang|=en])css(border3px dotted green)

        HTML

        lta href=examplehtml hreflang=engtSome textltagt

        lta href=examplehtml hreflang=en-UKgtSome other textltagt

        lta href=examplehtml hreflang=englishgtwill not be outl inedltagt

        CSS

        a display inl ine-block

        attributeContainsWord $([attribute~=value])

        Selects elements that have the specif ied at t ribute with a value containing a given worddelimited by spaces

        Added in version 10

        $([at t ribute~=value])

        at t ributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        This selector matches the test string against each word in the at t ribute value where a word isdef ined as a string delimited by whitespace The selector matches if the test string is exact lyequal to any of the words

        Example 1 Finds all inputs with a name attribute that contains the word man and sets the

        value with some text

        Javascript

        $( input[name~=man])val(mr man is in it)

        HTML

        ltinput name=man-news gt

        ltinput name=milk man gt ltinput name=letterman2 gt ltinput name=newmilk gt

        attributeMultiple$([attributeFilter1][attributeFilter2][attributeFilterN])

        Matches elements that match all of the specif ied at t ribute f ilters

        Added in version 10

        $([at t ributeFilter1][at t ributeFilter2][at t ributeFilterN])

        at t ributeFilter1Selector An at t ribute f ilter

        at t ributeFilter2Selector Another at t ribute f ilter reducing the select ion even more

        attributeFilterNSelector (opt ional) As many more at t ribute f ilters as necessary

        Example 1 Finds all inputs that have an id at t ribute and whose name attribute ends with manand sets the value

        Javascript

        $( input[id][name$=man])val(only this one)

        HTML

        ltinput id=man-news name=man-news gt

        ltinput name=milkman gt ltinput id=letterman name=new-letterman gt ltinput name=newmilk gt

        attributeContains $([attribute=value])

        Selects elements that have the specif ied at t ribute with a value containing the a given substring

        Added in version 10

        $([at t ribute=value])

        at t ributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        This is the most generous of the jQuery at t ribute selectors that match against a value It willselect an element if the selectors string appears anywhere within the element s at t ribute valueCompare this selector with the Attribute Contains Word selector (eg [at t r~=word]) which ismore appropriate in many cases

        Example 1 Finds all inputs with a name attribute that contains man and sets the value withsome text

        Javascript

        $( input[name=man])val(has man in it)

        HTML

        ltinput name=man-news gt

        ltinput name=milkman gt ltinput name=letterman2 gt ltinput name=newmilk gt

        attributeEndsWith $([attribute$=value])

        Selects elements that have the specif ied at t ribute with a value ending exact ly with a givenstring The comparison is case sensit ive

        Added in version 10

        $([at t ribute$=value])

        at t ributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        Example 1 Finds all inputs with an at t ribute name that ends with let ter and puts text in them

        Javascript

        $( input[name$=letter])val(a letter)

        HTML

        ltinput name=newsletter gt

        ltinput name=milkman gt ltinput name=jobletter gt

        attributeStartsWith $([attribute^=value])

        Selects elements that have the specif ied at t ribute with a value beginning exact ly with a givenstring

        Added in version 10

        $([at t ribute^=value])

        at t ributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        This selector can be useful for ident ifying elements in pages produced by server-sideframeworks that produce HTML with systemat ic element IDs However it will be slower thanusing a class selector so leverage classes if you can to group like elements

        Example 1 Finds all inputs with an at t ribute name that starts with news and puts text in them

        Javascript

        $( input[name^=news])val(news here)

        HTML

        ltinput name=newsletter gt

        ltinput name=milkman gt ltinput name=newsboy gt

        attributeNotEqual $([attribute=value])

        Select elements that either dont have the specif ied at t ribute or do have the specif ied at t ributebut not with a certain value

        Added in version 10

        $([at t ribute=value])

        at t ributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        This selector is equivalent to not([at t r=value])

        Example 1 Finds all inputs that dont have the name newslet ter and appends text to the spannext to it

        Javascript

        $( input[name=newsletter])next()append(ltbgt not newsletterltbgt)

        HTML

        ltdivgt

        ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtname is newsletterltspangt

        ltdivgt ltdivgt ltinput type=radio value=Cold Fusion gt ltspangtno nameltspangt

        ltdivgt ltdivgt ltinput type=radio name=accept value=Evil Plans gt

        ltspangtname is acceptltspangt ltdivgt

        attributeEquals $([attribute=value])

        Selects elements that have the specif ied at t ribute with a value exact ly equal to a certain value

        Added in version 10

        $([at t ribute=value])

        attributeString An at t ribute name

        valueString An at t ribute value Quotes are mandatory

        Example 1 Finds all inputs with a value of Hot Fuzz and changes the text of the next siblingspan

        Javascript

        $( input[value=Hot Fuzz])next()text( Hot Fuzz)

        HTML

        ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtnameltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Cold Fusion gt ltspangtvalueltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Evil Plans gt ltspangtvalueltspangt ltlabelgt ltdivgt

        attributeHas $([attribute])

        Selects elements that have the specif ied at t ribute with any value

        Added in version 10

        $([at t ribute])

        at t ributeString An at t ribute name

        Example 1 Bind a single click that adds the div id to its text

        Javascript

        $(div[id])one(cl ick function() var idString = $(this)text() + = + $(this)attr( id) $(this)text(idString) )

        HTML

        ltdivgtno idltdivgt ltdiv id=heygtwith idltdivgt

        ltdiv id=theregthas an idltdivgt ltdivgtnopeltdivgt

        visible $(visible)

        Selects all elements that are visible

        Added in version 10

        $(visible)

        Elements can be considered hidden for several reasons

        They have a CSS display value of none

        They are form elements with type=hidden

        Their width and height are explicit ly set to 0

        An ancestor element is hidden so the element is not shown on the page

        Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start at the animat ion

        How visible is calculated was changed in jQuery 132 The release notes out line the changes inmore detail

        Example 1 Make all visible divs turn yellow on click

        Javascript

        $(divvisible)cl ick(function () $(this)css(background yellow) ) $(button)cl ick(function () $(divhidden)show(fast) )

        CSS

        div width50px height40px margin5px border3px outset green floatleft starthidden displaynone

        HTML

        ltbuttongtShow hidden to see they dont changeltbuttongt ltdivgtltdivgt ltdiv class=starthiddengtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdiv style=displaynonegtltdivgt

        hidden $(hidden)

        Selects all elements that are hidden

        Added in version 10

        $(hidden)

        Elements can be considered hidden for several reasons

        They have a CSS display value of none

        They are form elements with type=hidden

        Their width and height are explicit ly set to 0

        An ancestor element is hidden so the element is not shown on the page

        Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start of the animat ion

        How hidden is determined was changed in jQuery 132 An element is assumed to be hidden if itor any of its parents consumes no space in the document CSS visibility isnt taken into account(therefore $(elem)css(visibilityhidden)is(hidden) == false) The release notes out line thechanges in more detail

        Example 1 Shows all hidden divs and counts hidden inputs

        Javascript

        in some browsers hidden includes head title script etcvar hiddenEls = $(body)find(hidden)not(script)

        $(spanfirst)text(Found + hiddenElslength + hidden elements total)$(divhidden)show(3000)$(spanlast)text(Found + $(inputhidden)length + hidden inputs)

        CSS

        div width70px height40px backgroundee77ff margin5px floatleft span displayblock clearleft colorred starthidden displaynone

        HTML

        ltspangtltspangt ltdivgtltdivgt ltdiv style=displaynonegtHiderltdivgt ltdivgtltdivgt

        ltdiv class=starthiddengtHiderltdivgt ltdivgtltdivgt ltformgt ltinput type=hidden gt

        ltinput type=hidden gt ltinput type=hidden gt ltformgt ltspangt

        ltspangt

        parent $(parent)

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

        Added in version 10

        $(parent)

        This is the inverse of empty

        One important thing to note regarding the use of parent (and empty) is that child elementsinclude text nodes

        The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elements

        on the other hand are empty (ie have no children) by def init ion ltinputgt ltimggt ltbrgt and lthrgtfor example

        Example 1 Finds all tds with children including text

        Javascript

        $(tdparent)fadeTo(1500 03)

        CSS

        td width40px backgroundgreen

        HTML

        lttable border=1gt

        lttrgtlttdgtValue 1lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtValue 2lttdgtlttdgtlttdgtlttrgt

        lttablegt

        has $(has(selector))

        Selects elements which contain at least one element that matches the specif ied selector

        Added in version 114

        $(has(selector))

        selectorSelector Any selector

        The expression $(divhas(p)) matches a ltdivgt if a ltpgt exists anywhere among its descendantsnot just as a direct child

        Example 1 Adds the class test to all divs that have a paragraph inside of them

        Javascript

        $(divhas(p))addClass(test)

        HTML

        ltdivgtltpgtHello in a paragraphltpgtltdivgt

        ltdivgtHello again (with no paragraph)ltdivgt

        CSS

        test border 3px inset red

        empty $(empty)

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

        Added in version 10

        $(empty)

        This is the inverse of parent

        One important thing to note with empty (and parent) is that child elements include text nodes

        The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elementson the other hand are empty (ie have no children) by def init ion and

        for example

        Example 1 Finds all elements that are empty - they dont have child elements or text

        Javascript

        $(tdempty)text(Was empty)css(background rgb(255220200))

        CSS

        td text-aligncenter

        HTML

        lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtTD 2lttdgtlttdgtlttdgtlttrgt

        lttrgtlttdgtlttdgtlttdgtTD5lttdgtlttrgt lttablegt

        contains $(contains(text))

        Select all elements that contain the specif ied text

        Added in version 114

        $(contains(text))

        text String A string of text to look for It s case sensit ive

        The matching text can appear direct ly within the selected element in any of that element sdescendants or a combinat ion thereof As with at t ribute value selectors text inside theparentheses of contains() can be writ ten as bare words or surrounded by quotat ion marks Thetext must have matching case to be selected

        Example 1 Finds all divs containing John and underlines them

        Javascript

        $(divcontains( John))css(text-decoration underline)

        HTML

        ltdivgtJohn Resigltdivgt

        ltdivgtGeorge MartinltdivgtltdivgtMalcom John SinclairltdivgtltdivgtJ Ohnltdivgt

        animated $(animated)

        Select all elements that are in the progress of an animat ion at the t ime the selector is run

        Added in version 12

        $(animated)

        Example 1 Change the color of any div that is animated

        Javascript

        $(run)cl ick(function() $(divanimated)toggleClass(colored) ) function animateIt() $(mover)sl ideToggle(slow animateIt) animateIt()

        HTML

        ltbutton id=rungtRunltbuttongt

        ltdivgtltdivgt ltdiv id=movergtltdivgt ltdivgtltdivgt

        CSS

        div backgroundyellow border1px solid AAA width80px height80px margin0 5px floatleft divcolored backgroundgreen

        header $(header)

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

        Added in version 12

        $(header)

        Example 1 Adds a background and text color to all the headers on the page

        Javascript

        $(header)css( backgroundCCC colorblue )

        HTML

        lth1gtHeader 1lth1gt

        ltpgtContents 1ltpgt lth2gtHeader 2lth2gt ltpgtContents 2ltpgt

        CSS

        body font-size 10px font-family Arial h1 h2 margin 3px 0

        lt $(lt(index))

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

        Added in version 10

        $(lt (index))

        indexNumber Zero-based index

        index-related selectors

        The index-related selectors (including this less than selector) f ilter the set of elements thathave matched the expressions that precede them They narrow the set down based on theorder of the elements within this matched set For example if elements are f irst selected with aclass selector (myclass) and four elements are returned these elements are given indices 0through 3 for the purposes of these selectors

        Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasslt (1)) selects the f irst element in the document with the class myclass ratherthan select ing no elements In contrast nth-child(n) uses 1-based indexing to conform to theCSS specif icat ion

        Example 1 Finds TDs less than the one with the 4th index (TD4)

        Javascript

        $(tdlt(4))css(color red)

        HTML

        lttable border=1gt

        lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

        lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

        gt $(gt(index))

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

        Added in version 10

        $(gt(index))

        indexNumber Zero-based index

        index-related selectors

        The index-related selector expressions (including this greater than selector) f ilter the set ofelements that have matched the expressions that precede them They narrow the set downbased on the order of the elements within this matched set For example if elements are f irstselected with a class selector (myclass) and four elements are returned these elements aregiven indices 0 through 3 for the purposes of these selectors

        Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclassgt(1)) selects elements af ter the second element in the document with theclass myclass rather than af ter the f irst In contrast nth-child(n) uses 1-based indexing toconform to the CSS specif icat ion

        Example 1 Finds TD 5 and higher Reminder the indexing starts at 0

        Javascript

        $(tdgt(4))css(text-decoration l ine-through)

        HTML

        lttable border=1gt

        lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt

        lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgt lttablegt

        eq $(eq(index))

        Select the element at index n within the matched set

        Added in version 10

        $(eq(index))

        indexNumber Zero-based index of the element to match

        The index-related selectors (eq() lt () gt() even odd) f ilter the set of elements that havematched the expressions that precede them They narrow the set down based on the order ofthe elements within this matched set For example if elements are f irst selected with a classselector (myclass) and four elements are returned these elements are given indices 0 through3 for the purposes of these selectors

        Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasseq(1)) selects the second element in the document with the class myclassrather than the f irst In contrast nth-child(n) uses 1-based indexing to conform to the CSSspecif icat ion

        Unlike the eq(index) method the eq(index) selector does not accept a negat ive value for indexFor example while $(li)eq(-1) selects the last li element $(lieq(-1)) selects nothing

        Example 1 Finds the third td

        Javascript

        $(tdeq(2))css(color red)

        HTML

        lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt

        Example 2 Apply three dif ferent styles to list items to demonstrate that eq() is designed toselect a single element while nth-child() or eq() within a looping construct such as each() canselect mult iple elements

        Javascript

        applies yellow background color to a single ltligt$(ulnav l i eq(1))css( backgroundColor ff0 )

        applies ital ics to text of the second ltligt within each ltul class=navgt$(ulnav)each(function(index) $(this)find(l i eq(1))css( fontStyle ital ic ))

        applies red text color to descendants of ltul class=navgt for each ltligt that is the second child of its parent$(ulnav l i nth-child(2))css( color red )

        HTML

        ltul class=navgt ltligtList 1 item 1ltligt ltligtList 1 item 2ltligt ltligtList 1 item 3ltligtltulgtltul class=navgt ltligtList 2 item 1ltligt ltligtList 2 item 2ltligt ltligtList 2 item 3ltligtltulgt

        odd $(odd)

        Selects odd elements zero-indexed See also even

        Added in version 10

        $(odd)

        In part icular note that the 0-based indexing means that counter-intuit ively odd selects thesecond element fourth element and so on within the matched set

        Example 1 Finds odd table rows matching the second fourth and so on (index 1 3 5 etc)

        Javascript

        $(trodd)css(background-color bbbbff)

        CSS

        table backgroundf3f7f5

        HTML

        lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

        lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

        even $(even)

        Selects even elements zero-indexed See also odd

        Added in version 10

        $(even)

        In part icular note that the 0-based indexing means that counter-intuit ively even selects thef irst element third element and so on within the matched set

        Example 1 Finds even table rows matching the f irst third and so on (index 0 2 4 etc)

        Javascript

        $(treven)css(background-color bbbbff)

        CSS

        table backgroundeeeeee

        HTML

        lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt

        lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt

        not $(not(selector))

        Selects all elements that do not match the given selector

        Added in version 10

        $(not(selector))

        selectorSelector A selector with which to f ilter by

        All selectors are accepted inside not() for example not(div a) and not(diva)

        Additional Notes

        The not() method will end up providing you with more readable select ions than pushingcomplex selectors or variables into a not() selector f ilter In most cases it is a better choice

        Example 1 Finds all inputs that are not checked and highlights the next sibling span Not icethere is no change when clicking the checkboxes since no click events have been linked

        Javascript

        $(inputnot(checked) + span)css(background-color yellow) $(input)attr(disabled disabled)

        HTML

        ltdivgt ltinput type=checkbox name=a gt ltspangtMaryltspangtltdivgt

        ltdivgt ltinput type=checkbox name=b gt ltspangtlcmltspangt

        ltdivgtltdivgt ltinput type=checkbox name=c checked=checked gt

        ltspangtPeterltspangtltdivgt

        last $(last)

        Selects the last matched element

        Added in version 10

        $(last)

        Note that last selects a single element by f iltering the current jQuery collect ion and matchingthe last element within it

        Example 1 Finds the last table row

        Javascript

        $(trlast)css(backgroundColor yellow fontWeight bolder)

        HTML

        lttablegt

        lttrgtlttdgtFirst Rowlttdgtlttrgt lttrgtlttdgtMiddle Rowlttdgtlttrgt lttrgtlttdgtLast Rowlttdgtlttrgt

        lttablegt

        first $(first)

        Selects the f irst matched element

        Added in version 10

        $(f irst)

        The f irst pseudo-class is equivalent to eq(0) It could also be writ ten as lt (1) While thismatches only a single element f irst-child can match more than one One for each parent

        Example 1 Finds the f irst table row

        Javascript

        $(trfirst)css(font-style ital ic)

        CSS

        td colorblue font-weightbold

        HTML

        lttablegt lttrgtlttdgtRow 1lttdgtlttrgt lttrgtlttdgtRow 2lttdgtlttrgt

        lttrgtlttdgtRow 3lttdgtlttrgt lttablegt

        next siblings $(prev ~ siblings)

        Selects all sibling elements that follow af ter the prev element have the same parent andmatch the f iltering siblings selector

        Added in version 10

        $(prev ~ siblings)

        prevSelector Any valid selector

        siblingsSelector A selector to f ilter elements that are the following siblings of the f irstselector

        The notable dif ference between (prev + next) and (prev ~ siblings) is their respect ive reachWhile the former reaches only to the immediately following sibling element the lat ter extendsthat reach to all following sibling elements

        Example 1 Finds all divs that are siblings af ter the element with prev as its id Not ice the spanisnt selected since it is not a div and the niece isnt selected since it is a child of a sibling notan actual sibling

        Javascript

        $(prev ~ div)css(border 3px groove blue)

        CSS

        divspan displayblock width80px height80px margin5px backgroundbbffaa floatleft font-size14px divsmall width60px height25px font-size12px backgroundfab

        HTML

        ltdivgtdiv (doesnt match since before prev)ltdivgt ltspan id=prevgtspanprevltspangt ltdivgtdiv siblingltdivgt

        ltdivgtdiv sibling ltdiv id=smallgtdiv nieceltdivgtltdivgt ltspangtspan sibling (not div)ltspangt ltdivgtdiv siblingltdivgt

        next adjacent $(prev + next)

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

        Added in version 10

        $(prev + next)

        prevSelector Any valid selector

        nextSelector A selector to match the element that is next to the f irst selector

        One important point to consider with both the next adjacent sibling selector (prev + next) andthe general sibling selector (prev ~ siblings) is that the elements on either side of thecombinator must share the same parent

        Example 1 Finds all inputs that are next to a label

        Javascript

        $(label + input)css(color blue)val(Labeled)

        HTML

        ltformgt

        ltlabelgtNameltlabelgt ltinput name=name gt ltfieldsetgt ltlabelgtNewsletterltlabelgt

        ltinput name=newsletter gt ltfieldsetgt ltformgt ltinput name=none gt

        child $(parent gt child)

        Selects all direct child elements specif ied by child of elements specif ied by parent

        Added in version 10

        $(parent gt child)

        parentSelector Any valid selector

        childSelector A selector to f ilter the child elements

        As a CSS selector the child combinator is supported by all modern web browsers includingSafari Firefox Opera Chrome and Internet Explorer 7 and above but notably not by InternetExplorer versions 6 and below However in jQuery this selector (along with all others) worksacross all supported browsers including IE6

        The child combinator (E gt F) can be thought of as a more specif ic form of the descendantcombinator (E F) in that it selects only f irst-level descendants

        Note The $(gt elem context) selector will be deprecated in a future release Itsusage is thus discouraged in lieu of using alternative selectors

        Example 1 Places a border around all list items that are children of

        Javascript

        $(ultopnav gt l i)css(border 3px double red)

        CSS

        body font-size14px

        HTML

        ltul class=topnavgt ltligtItem 1ltligt ltligtItem 2 ltulgtltligtNested item 1ltligtltligtNested item 2ltligtltligtNested item 3ltligtltulgt ltl igt ltligtItem 3ltligtltulgt

        descendant $(ancestor descendant)

        Selects all elements that are descendants of a given ancestor

        Added in version 10

        $(ancestor descendant)

        ancestorSelector Any valid selector

        descendantSelector A selector to f ilter the descendant elements

        A descendant of an element could be a child grandchild great-grandchild and so on of thatelement

        Example 1 Finds all input descendants of forms

        Javascript

        $(form input)css(border 2px dotted blue)

        CSS

        body font-size14px form border2px green solid padding2px margin0 backgroundefe div colorred fieldset margin1px padding3px

        HTML

        ltformgt ltdivgtForm is surrounded by the green outl ineltdivgt ltlabelgtChildltlabelgt ltinput name=name gt

        ltfieldsetgt ltlabelgtGrandchildltlabelgt ltinput name=newsletter gt ltfieldsetgt

        ltformgt Sibling to form ltinput name=none gt

        multiple $(selector1 selector2 selectorN)

        Selects the combined results of all the specif ied selectors

        Added in version 10

        $(selector1 selector2 selectorN)

        selector1Selector Any valid selector

        selector2Selector Another valid selector

        selectorNSelector (opt ional) As many more valid selectors as you like

        You can specify any number of selectors to combine into a single result This mult ipleexpression combinator is an ef f icient way to select disparate elements The order of the DOMelements in the returned jQuery object may not be ident ical as they will be in document orderAn alternat ive to this combinator is the add() method

        Example 1 Finds the elements that match any of these three selectors

        Javascript

        $(divspanpmyClass)css(border3px solid red)

        HTML

        ltdivgtdivltdivgt

        ltp class=myClassgtp class=myClassltpgt ltp class=notMyClassgtp class=notMyClassltpgt ltspangtspanltspangt

        CSS

        divspanp width 126px height 60px floatleft padding 3px margin 2px background-color EEEEEE font-size14px

        Example 2 Show the order in the jQuery object

        Javascript

        var l ist = $(divpspan)map(function () return thistagName )get()join( ) $(b)append(documentcreateTextNode(list))

        CSS

        b colorred font-size16px displayblock clearleft divspanp width 40px height 40px floatleft margin 10px background-color blue padding3px colorwhite

        HTML

        ltspangtspanltspangt

        ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt ltspangtspanltspangt

        ltpgtpltpgt ltdivgtdivltdivgt ltbgtltbgt

        all $()

        Selects all elements

        Added in version 10

        $()

        Caut ion The all or universal selector is extremely slow except when used by itself

        Example 1 Finds every element (including head body etc) in the document

        Javascript

        var elementCount = $()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

        HTML

        ltdivgtDIVltdivgt

        ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgt

        CSS

        h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE

        Example 2 A common way to select all elements is to f ind within documentbody so elementslike head script etc are lef t out

        Javascript

        var elementCount = $(test)find()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)

        HTML

        ltdiv id=testgt ltdivgtDIVltdivgt ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgtltdivgt

        CSS

        h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE test width auto height auto background-color transparent

        class $(class)

        Selects all elements with the given class

        Added in version 10

        $(class)

        classString A class to search for An element can have mult iple classes only one ofthem must match

        For class selectors jQuery uses JavaScript s nat ive getElementsByClassName() funct ion if thebrowser supports it

        Example 1 Finds the element with the class myClass

        Javascript

        $(myClass)css(border3px solid red)

        HTML

        ltdiv class=notMegtdiv class=notMeltdivgt

        ltdiv class=myClassgtdiv class=myClassltdivgt ltspan class=myClassgtspan class=myClassltspangt

        CSS

        divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

        Example 2 Finds the element with both myclass and otherclass classes

        Javascript

        $(myclassotherclass)css(border13px solid red)

        HTML

        ltdiv class=myclassgtdiv class=notMeltdivgt

        ltdiv class=myclass otherclassgtdiv class=myClassltdivgt ltspan class=myclass otherclassgtspan class=myClassltspangt

        CSS

        divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE

        element $(element)

        Selects all elements with the given tag name

        Added in version 10

        $(element)

        elementString An element to search for Refers to the tagName of DOM nodes

        JavaScript s getElementsByTagName() funct ion is called to return the appropriate elementswhen this expression is used

        Example 1 Finds every DIV element

        Javascript

        $(div)css(border9px solid red)

        HTML

        ltdivgtDIV1ltdivgt

        ltdivgtDIV2ltdivgt ltspangtSPANltspangt

        CSS

        divspan width 60px height 60px floatleft padding 10px margin 10px background-color EEEEEE

        id $(id)

        Selects a single element with the given id at t ribute

        Added in version 10

        $( id)

        idString An ID to search for specif ied via the id at t ribute of an element

        For id selectors jQuery uses the JavaScript funct ion documentgetElementById() which isextremely ef f icient When another selector is at tached to the id selector such as h2pageTit lejQuery performs an addit ional check before ident ifying the element as a match

        As always remember that as a developer your time is typically the most valuableresource Do not focus on optimization of selector speed unless it is clear thatperformance needs to be improved

        Each id value must be used only once within a document If more than one element has beenassigned the same ID queries that use that ID will only select the f irst matched element in theDOM This behavior should not be relied on however a document with more than one elementusing the same ID is invalid

        If the id contains characters like periods or colons you have to escape those characters withbackslashes

        Example 1 Finds the element with the id myDiv

        Javascript

        $(myDiv)css(border3px solid red)

        HTML

        ltdiv id=notMegtltpgtid=notMeltpgtltdivgt

        ltdiv id=myDivgtid=myDivltdivgt

        CSS

        div width 90px height 90px floatleft padding 5px margin 5px background-color EEEEEE

        Example 2 Finds the element with the id myIDentry[1] See how certain characters must beescaped with backslashes

        Javascript

        $(myIDentry[1])css(border3px solid red)

        HTML

        ltdiv id=myIDentry[0]gtid=myIDentry[0]ltdivgt

        ltdiv id=myIDentry[1]gtid=myIDentry[1]ltdivgt ltdiv id=myIDentry[2]gtid=myIDentry[2]ltdivgt

        CSS

        div width 300px floatleft padding 2px margin 3px background-color EEEEEE

        Traversing

        has

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

        Added in version 14

        has(contained)jQuery

        containedElement A DOM element to match elements against

        Given a jQuery object that represents a set of DOM elements the has() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst the descendants of the matching elements the element will be included in the result ifany of its descendant elements matches the selector

        Consider a page with a nested list as follows

        ltulgt ltligtlist item 1ltligt ltligtlist item 2 ltulgt ltligtlist item 2-altligt ltligtlist item 2-bltligt ltulgt ltl igt ltligtlist item 3ltligt ltligtlist item 4ltligtltulgt

        We can apply this method to the set of list items as follows

        $( l i )has(ul )css(background-color red)

        The result of this call is a red background for item 2 as it is the only ltligt that has a ltulgt amongits descendants

        Example 1 Check if an element is inside another

        Javascript

        $(ul)append(ltligt + ($(ul)has(l i)length Yes No) + ltl igt) $(ul)has(l i)addClass(full)

        CSS

        ful l border 1px solid red

        HTML

        ltulgtltligtDoes the UL contain an LIltl igtltulgt

        parentsUntil

        Get the ancestors of each element in the current set of matched elements up to but notincluding the element matched by the selector DOM node or jQuery object

        Added in version 16

        parentsUnt il(element f ilter)jQuery

        elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching ancestor elements

        f ilterSelector (opt ional) A string containing a selector expression to matchelements against

        Given a selector expression that represents a set of DOM elements the parentsUnt il() methodtraverses through the ancestors of these elements unt il it reaches an element matched by theselector passed in the methods argument The result ing jQuery object contains all of theancestors up to but not including the one matched by the parentsUnt il() selector

        If the selector is not matched or is not supplied all ancestors will be selected in these cases itselects the same elements as the parents() method does when no selector is provided

        As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstparentsUnt il() argument

        The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

        Example 1 Find the ancestors of

        up to

        and give them a red background color Also f ind ancestors of

        that have a class of yes up toand give them a green border

        Javascript

        $(l i item-a)parentsUntil(level-1) css(background-color red)

        $(l i item-2)parentsUntil( $(ullevel-1) yes ) css(border 3px solid green)

        HTML

        ltul class=level-1 yesgt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2 yesgt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        prevUntil

        Get all preceding siblings of each element up to but not including the element matched by theselector DOM node or jQuery object

        Added in version 16

        prevUnt il(element f ilter)jQuery

        elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching preceding sibling elements

        f ilterSelector (opt ional) A string containing a selector expression to matchelements against

        Given a selector expression that represents a set of DOM elements the prevUnt il() methodsearches through the predecessors of these elements in the DOM tree stopping when itreaches an element matched by the methods argument The new jQuery object that isreturned contains all previous siblings up to but not including the one matched by theprevUnt il() selector the elements are returned in order f rom the closest sibling to the farthest

        If the selector is not matched or is not supplied all previous siblings will be selected in thesecases it selects the same elements as the prevAll() method does when no f ilter selector isprovided

        As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstprevUnt il() argument

        The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

        Example 1 Find the siblings that precede

        up to the precedingand give them a red background color Also f ind previous

        siblings ofup toand give them a green text color

        Javascript

        $(term-2)prevUntil(dt) css(background-color red) var term1 = documentgetElementById(term-1)$(term-3)prevUntil(term1 dd) css(color green)

        HTML

        ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

        ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

        ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

        nextUntil

        Get all following siblings of each element up to but not including the element matched by theselector DOM node or jQuery object passed

        Added in version 16

        nextUnt il(element f ilter)jQuery

        elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching following sibling elements

        f ilterSelector (opt ional) A string containing a selector expression to matchelements against

        Given a selector expression that represents a set of DOM elements the nextUnt il() methodsearches through the successors of these elements in the DOM tree stopping when it reachesan element matched by the methods argument The new jQuery object that is returnedcontains all following siblings up to but not including the one matched by the nextUnt il()argument

        If the selector is not matched or is not supplied all following siblings will be selected in thesecases it selects the same elements as the nextAll() method does when no f ilter selector isprovided

        As of jQuery 16 A DOM node or jQuery object instead of a selector may be passed to thenextUnt il() method

        The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it

        Example 1 Find the siblings that follow

        up to the nextand give them a red background color Also f ind

        siblings that followup toand give them a green text color

        Javascript

        $(term-2)nextUntil(dt) css(background-color red)

        var term3 = documentgetElementById(term-3)$(term-1)nextUntil(term3 dd) css(color green)

        HTML

        ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt

        ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt

        ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt

        each

        Iterate over a jQuery object execut ing a funct ion for each matched element

        Added in version 10

        each(funct ion(index Element))jQuery

        funct ion(index Element)Funct ion A funct ion to execute for each matched element

        The each() method is designed to make DOM looping constructs concise and less error-proneWhen called it iterates over the DOM elements that are part of the jQuery object Each t ime thecallback runs it is passed the current loop iterat ion beginning from 0 More important ly thecallback is f ired in the context of the current DOM element so the keyword this refers to theelement

        Suppose we had a simple unordered list on the page

        ltulgt ltligtfooltligt ltligtbarltligt ltulgt

        We can select the list items and iterate across them

        $( l i )each(function(index) alert(index + + $(this)text()) )

        A message is thus alerted for each item in the list

        0 foo

        1 bar

        We can stop the loop from within the callback funct ion by returning false

        Example 1 Iterates over three divs and sets their color property

        Javascript

        $(documentbody)cl ick(function () $(div)each(function (i) i f (thisstylecolor = blue) thisstylecolor = blue else thisstylecolor = ) )

        CSS

        div colorred text-aligncenter cursorpointer font-weightbolder width300px

        HTML

        ltdivgtClick hereltdivgt

        ltdivgtto iterate throughltdivgt ltdivgtthese divsltdivgt

        Example 2 If you want to have the jQuery object instead of the regular DOM element use the$(this) funct ion for example

        Javascript

        $(span)cl ick(function () $(l i)each(function() $(this)toggleClass(example) ) )

        CSS

        ul font-size18px margin0 span colorblue text-decorationunderline cursorpointer example font-styleital ic

        HTML

        To do l ist ltspangt(click here to change)ltspangt ltulgt ltligtEatltligt ltligtSleepltligt

        ltligtBe merryltligt ltulgt

        Example 3 You can use return to break out of each() loops early

        Javascript

        $(button)cl ick(function () $(div)each(function (index domEle) domEle == this $(domEle)css(backgroundColor yellow) i f ($(this)is(stop)) $(span)text(Stopped at div index + index) return false ) )

        CSS

        div width40px height40px margin5px floatleft border2px blue solid text-aligncenter span colorred

        HTML

        ltbuttongtChange colorsltbuttongt ltspangtltspangt ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdiv id=stopgtStop hereltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt

        first

        Reduce the set of matched elements to the f irst in the set

        Added in version 14

        f irst()jQuery

        [

        Given a jQuery object that represents a set of DOM elements the f irst() method constructs anew jQuery object f rom the f irst matching element

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        We can apply this method to the set of list items

        $( l i )first()css(background-color red)

        The result of this call is a red background for the f irst item

        Example 1 Highlight the f irst span in a paragraph

        CSS

        highlightbackground-color yellow

        Javascript

        $(p span)first()addClass(highlight)

        HTML

        ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

        last

        Reduce the set of matched elements to the f inal one in the set

        Added in version 14

        last()jQuery

        [

        Given a jQuery object that represents a set of DOM elements the last() method constructs anew jQuery object f rom the last matching element

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        We can apply this method to the set of list items

        $( l i )last()css(background-color red)

        The result of this call is a red background for the f inal item

        Example 1 Highlight the last span in a paragraph

        CSS

        highlightbackground-color yellow

        Javascript

        $(p span)last()addClass(highlight)

        HTML

        ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt

        slice

        Reduce the set of matched elements to a subset specif ied by a range of indices

        Added in version 114

        slice(start end)jQuery

        start Integer An integer indicat ing the 0-based posit ion at which the elements begin tobe selected If negat ive it indicates an of fset f rom the end of the set

        endInteger (opt ional) An integer indicat ing the 0-based posit ion at which theelements stop being selected If negat ive it indicates an of fset f rom theend of the set If omit ted the range cont inues unt il the end of the set

        Given a jQuery object that represents a set of DOM elements the slice() method constructs anew jQuery object f rom a subset of the matching elements The supplied start index ident if iesthe posit ion of one of the elements in the set if end is omit ted all elements af ter this one willbe included in the result

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        We can apply this method to the set of list items

        $( l i )sl ice(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 iszero-based and refers to the posit ion of elements within the jQuery object not within theDOM tree

        The end parameter allows us to limit the selected range even further For example

        $( l i )sl ice(2 4)css(background-color red)

        Now only items 3 and 4 are selected The index is once again zero-based the range extends upto but not including the specif ied index

        Negative Indices

        The jQuery slice() method is patterned af ter the JavaScript slice() method for arrays One ofthe features that it mimics is the ability for negat ive numbers to be passed as either the start orend parameter If a negat ive number is provided this indicates a posit ion start ing f rom the endof the set rather than the beginning For example

        $( l i )sl ice(-2 -1)css(background-color red)

        This t ime only list item 4 is turned red since it is the only item in the range between two fromthe end (-2) and one from the end (-1)

        Example 1 Turns divs yellow based on a random slice

        Javascript

        function colorEm() var $div = $(div) var start = Mathfloor(Mathrandom() $divlength) var end = Mathfloor(Mathrandom() ($divlength - start)) + start + 1 i f (end == $divlength) end = undefined $divcss(background ) i f (end) $divsl ice(start end)css(background yellow) else $divsl ice(start)css(background yellow) $(span)text($(div)sl ice( + start + (end + end ) + )css(background yellow))

        $(button)cl ick(colorEm)

        CSS

        div width40px height40px margin10px floatleft border2px solid blue span colorred font-weightbold button margin5px

        HTML

        ltpgtltbuttongtTurn sl ice yellowltbuttongt ltspangtClick the buttonltspangtltpgt ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt

        Example 2 Selects all paragraphs then slices the select ion to include only the f irst element

        Javascript

        $(p)sl ice(0 1)wrapInner(ltbgtltbgt)

        Example 3 Selects all paragraphs then slices the select ion to include only the f irst and secondelement

        Javascript

        $(p)sl ice(0 2)wrapInner(ltbgtltbgt)

        Example 4 Selects all paragraphs then slices the select ion to include only the second element

        Javascript

        $(p)sl ice(1 2)wrapInner(ltbgtltbgt)

        Example 5 Selects all paragraphs then slices the select ion to include only the second and thirdelement

        Javascript

        $(p)sl ice(1)wrapInner(ltbgtltbgt)

        Example 6 Selects all paragraphs then slices the select ion to include only the third element

        Javascript

        $(p)sl ice(-1)wrapInner(ltbgtltbgt)

        end

        End the most recent f iltering operat ion in the current chain and return the set of matchedelements to its previous state

        Added in version 10

        end()jQuery

        Most of jQuerys DOM traversal methods operate on a jQuery object instance and produce anew one matching a dif ferent set of DOM elements When this happens it is as if the new setof elements is pushed onto a stack that is maintained inside the object Each successivef iltering method pushes a new element set onto the stack If we need an older element set wecan use end() to pop the sets back of f of the stack

        Suppose we have a couple short lists on a page

        ltul class=firstgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgtltul class=secondgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgt

        The end() method is useful primarily when exploit ing jQuerys chaining propert ies When notusing chaining we can usually just call up a previous object by variable name so we dont needto manipulate the stack With end() though we can string all the method calls together

        $(ulfirst)find(foo)css(background-color red) end()find(bar)css(background-color green)

        This chain searches for items with the class foo within the f irst list only and turns theirbackgrounds red Then end() returns the object to its state before the call to f ind() so thesecond f ind() looks for bar inside ltul class=f irstgt not just inside that list s ltli class=foogtand turns the matching elements backgrounds green The net result is that items 1 and 3 ofthe f irst 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 f iltering methodsproviding the openings of nested blocks and end() methods closing them

        $(ulfirst)find(foo) css(background-color red)end()find(bar) css(background-color green)end()

        The last end() is unnecessary as we are discarding the jQuery object immediately thereafterHowever when the code is writ ten in this form the end() provides visual symmetry and a senseof complet ion acirceurordquomaking the program at least to the eyes of some developers more readableat the cost of a slight hit to performance as it is an addit ional funct ion call

        Example 1 Selects all paragraphs f inds span elements inside these and reverts the select ionback to the paragraphs

        Javascript

        jQueryfnshowTags = function (n) var tags = thismap(function () return thistagName ) get()join( ) $(beq( + n + ))text(tags) return this

        $(p)showTags(0) find(span) showTags(1) css(background yellow) end() showTags(2) css(font-style ital ic)

        CSS

        p div margin1px padding1px font-weightbold font-size16px div colorblue b colorred

        HTML

        ltpgt Hi there ltspangthowltspangt are you ltspangtdoingltspangt ltpgt

        ltpgt This ltspangtspanltspangt is one of several ltspangtspansltspangt in this ltspangtsentenceltspangt ltpgt

        ltdivgt Tags in jQuery object initial ly ltbgtltbgt ltdivgt ltdivgt Tags in jQuery object after find ltbgtltbgt

        ltdivgt ltdivgt Tags in jQuery object after end ltbgtltbgt ltdivgt

        Example 2 Selects all paragraphs f inds span elements inside these and reverts the select ion

        back to the paragraphs

        Javascript

        $(p)find(span)end()css(border 2px red solid)

        CSS

        p margin10px padding10px

        HTML

        ltpgtltspangtHelloltspangt how are youltpgt

        andSelf

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

        Added in version 12

        andSelf()jQuery

        As described in the discussion for end() jQuery objects maintain an internal stack that keepstrack of changes to the matched set of elements When one of the DOM traversal methods iscalled the new set of elements is pushed onto the stack If the previous set of elements isdesired as well andSelf() can help

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        The result of the following code is a red background behind items 3 4 and 5

        $( l i third-item)nextAll()andSelf() css(background-color red)

        First the init ial selector locates item 3 init ializing the stack with the set containing just this itemThe call to nextAll() then pushes the set of items 4 and 5 onto the stack Finally the andSelf()invocat ion merges these two sets together creat ing a jQuery object that points to all three

        items in document order [ltlithird-itemgtltligtltligt ]

        Example 1 Find all divs and all the paragraphs inside of them and give them both class namesNot ice the div doesnt have the yellow background color since it didnt use andSelf()

        Javascript

        $(div)find(p)andSelf()addClass(border) $(div)find(p)addClass(background)

        CSS

        p div margin5px padding5px border border 2px solid red background backgroundyellow

        HTML

        ltdivgt ltpgtFirst Paragraphltpgt ltpgtSecond Paragraphltpgt ltdivgt

        siblings

        Get the siblings of each element in the set of matched elements opt ionally f iltered by aselector

        Added in version 10

        siblings(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the siblings() method allows usto search through the siblings of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        If we begin at the third item we can f ind its siblings

        $( l i 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 aselector expression all of the siblings are part of the object If we had supplied one only thematching items among these four would be included

        The original element is not included among the siblings which is important to remember whenwe wish to f ind all elements at a part icular level of the DOM tree

        Example 1 Find the unique siblings of all yellow li elements in the 3 lists (including other yellow lielements if appropriate)

        Javascript

        var len = $(hil ite)siblings() css(color red) length $(b)text(len)

        CSS

        ul floatleft margin5px font-size16px font-weightbold p colorblue margin10px 20px font-size16px padding5px font-weightbolder hi l ite backgroundyellow

        HTML

        ltulgt ltligtOneltligt

        ltligtTwoltligt ltli class=hil itegtThreeltligt ltligtFourltligt ltulgt

        ltulgt ltligtFiveltligt ltligtSixltligt ltligtSevenltligt

        ltulgt ltulgt ltligtEightltligt ltli class=hil itegtNineltligt

        ltligtTenltligt ltli class=hil itegtElevenltligt ltulgt ltpgtUnique siblings ltbgtltbgtltpgt

        Example 2 Find all siblings with a class selected of each div

        Javascript

        $(p)siblings(selected)css(background yellow)

        HTML

        ltdivgtltspangtHelloltspangtltdivgt

        ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

        prevAll

        Get all preceding siblings of each element in the set of matched elements opt ionally f iltered bya selector

        Added in version 12

        prevAll(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the prevAll() method searchesthrough the predecessors of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements the elements are returned in order beginning with theclosest sibling

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        If we begin at the third item we can f ind the elements which come before it

        $( l i 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 aselector 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

        Example 1 Locate all the divs preceding the last div and give them a class

        Javascript

        $(divlast)prevAll()addClass(before)

        CSS

        div width70px height70px backgroundabc border2px solid black margin10px floatleft divbefore border-color red

        HTML

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        prev

        Get the immediately preceding sibling of each element in the set of matched elementsopt ionally f iltered by a selector

        Added in version 10

        prev(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the prev() method allows us tosearch through the predecessors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        If we begin at the third item we can f ind the element which comes just before it

        $( l i 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 selectorexpression this preceding element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

        Example 1 Find the very previous sibling of each div

        Javascript

        var $curr = $(start) $currcss(background f99) $(button)cl ick(function () $curr = $currprev() $(div)css(background ) $currcss(background f99) )

        CSS

        div width40px height40px margin10px floatleft border2px blue solid padding2px span font-size14px p clearleft margin10px

        HTML

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltspangthas childltspangtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdiv id=startgtltdivgt

        ltdivgtltdivgt ltpgtltbuttongtGo to Prevltbuttongtltpgt

        Example 2 For each paragraph f ind the very previous sibling that has a class selected

        Javascript

        $(p)prev(selected)css(background yellow)

        HTML

        ltdivgtltspangtHelloltspangtltdivgt

        ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt

        parents

        Get the ancestors of each element in the current set of matched elements opt ionally f iltered

        by a selector

        Added in version 10

        parents(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the parents() method allows usto search through the ancestors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements ordered from immediate parent on up the elementsare returned in order f rom the closest parent to the outer ones The parents() and parent()methods are similar except that the lat ter only t ravels a single level up the DOM tree

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a basic nested list on it

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        If we begin at item A we can f ind its ancestors

        $( l i 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 onup the DOM tree all the way to the lthtmlgt element) Since we do not supply a selectorexpression 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

        Example 1 Find all parent elements of each b

        Javascript

        var parentEls = $(b)parents() map(function () return thistagName ) get()join( )$(b)append(ltstronggt + parentEls + ltstronggt)

        CSS

        b span p html body padding 5em border 1px solid b colorblue strong colorred

        HTML

        ltdivgt ltpgt ltspangt ltbgtMy parents are ltbgt ltspangt

        ltpgt ltdivgt

        Example 2 Click to f ind all unique div parent elements of each span

        Javascript

        function showParents() $(div)css(border-color white) var len = $(spanselected) parents(div) css(border 2px red solid) length $(b)text(Unique div parents + len)$(span)cl ick(function () $(this)toggleClass(selected) showParents())

        CSS

        p div span margin2px padding1px div border2px white solid span cursorpointer font-size12px selected colorblue b colorred displayblock font-size14px

        HTML

        ltpgt ltdivgt ltdivgtltspangtHelloltspangtltdivgt ltspangtHello Againltspangt

        ltdivgt ltdivgt ltspangtAnd Hello Againltspangt ltdivgt ltpgt

        ltbgtClick Hellos to toggle their parentsltbgt

        parent

        Get the parent of each element in the current set of matched elements opt ionally f iltered by aselector

        Added in version 10

        parent(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the parent() method allows usto search through the parents of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements The parents() and parent() methods are similar exceptthat the lat ter only t ravels a single level up the DOM tree

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a basic nested list on it

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        If we begin at item A we can f ind its parents

        $( l i 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 selectorexpression the parent element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included

        Example 1 Shows the parent of each element as (parent gt child) Check the View Source tosee the raw html

        Javascript

        $( documentbody)each(function () var parentTag = $(this)parent()get(0)tagName $(this)prepend(documentcreateTextNode(parentTag + gt )) )

        CSS

        divp margin10px

        HTML

        ltdivgtdiv ltspangtspan ltspangt ltbgtb ltbgt

        ltdivgt ltpgtp ltspangtspan ltemgtem ltemgt ltspangt ltpgt

        ltdivgtdiv ltstronggtstrong ltspangtspan ltspangt ltemgtem ltbgtb ltbgt ltemgt

        ltstronggt ltbgtb ltbgt ltdivgt

        Example 2 Find the parent element of each paragraph with a class selected

        Javascript

        $(p)parent(selected)css(background yellow)

        HTML

        ltdivgtltpgtHelloltpgtltdivgt

        ltdiv class=selectedgtltpgtHello Againltpgtltdivgt

        offsetParent

        Get the closest ancestor element that is posit ioned

        Added in version 126

        offsetParent()jQuery

        Given a jQuery object that represents a set of DOM elements the of fsetParent() methodallows us to search through the ancestors of these elements in the DOM tree and construct anew jQuery object wrapped around the closest posit ioned ancestor An element is said to beposit ioned if it has a CSS posit ion at t ribute of relat ive absolute or f ixed This informat ion isuseful for calculat ing of fsets for performing animat ions and placing objects on the page

        Consider a page with a basic nested list on it with a posit ioned element

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        If we begin at item A we can f ind its posit ioned ancestor

        $( l i item-a)offsetParent()css(background-color red)

        This will change the color of list item II which is posit ioned

        Example 1 Find the of fsetParent of item A

        Javascript

        $( l i item-a)offsetParent()css(background-color red)

        HTML

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igt ltulgt

        nextAll

        Get all following siblings of each element in the set of matched elements opt ionally f iltered bya selector

        Added in version 12

        nextAll(selector)jQuery

        selectorString (opt ional) A string containing a selector expression to match elementsagainst

        Given a jQuery object that represents a set of DOM elements the nextAll() method allows usto search through the successors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        If we begin at the third item we can f ind the elements which come after it

        $( l i 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 aselector 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

        Example 1 Locate all the divs af ter the f irst and give them a class

        Javascript

        $(divfirst)nextAll()addClass(after)

        CSS

        div width 80px height 80px background abc border 2px solid black margin 10px float left divafter border-color red

        HTML

        ltdivgtfirstltdivgt ltdivgtsiblingltdivgtchildltdivgtltdivgt ltdivgtsiblingltdivgt

        ltdivgtsiblingltdivgt

        Example 2 Locate all the paragraphs af ter the second child in the body and give them a class

        Javascript

        $(nth-child(1))nextAll(p)addClass(after)

        CSS

        div p width 60px height 60px background abc border 2px solid black margin 10px float left after border-color red

        HTML

        ltpgtpltpgt

        ltdivgtdivltdivgt ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt

        ltpgtpltpgt ltdivgtdivltdivgt

        next

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

        Added in version 10

        next(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the next() method allows us tosearch through the immediately following sibling of these elements in the DOM tree andconstruct a new jQuery object f rom the matching elements

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the immediately following sibling matches the selector it remains in the newlyconstructed jQuery object otherwise it is excluded

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        If we begin at the third item we can f ind the element which comes just af ter it

        $( l i 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 hadsupplied one the element would be tested for a match before it was included

        Example 1 Find the very next sibling of each disabled button and change its text this button isdisabled

        Javascript

        $(button[disabled])next()text(this button is disabled)

        CSS

        span colorblue font-weightbold button width100px

        HTML

        ltdivgtltbutton disabled=disabledgtFirstltbuttongt - ltspangtltspangtltdivgt ltdivgtltbuttongtSecondltbuttongt - ltspangtltspangtltdivgt

        ltdivgtltbutton disabled=disabledgtThirdltbuttongt - ltspangtltspangtltdivgt

        Example 2 Find the very next sibling of each paragraph Keep only the ones with a classselected

        Javascript

        $(p)next(selected)css(background yellow)

        HTML

        ltpgtHelloltpgt

        ltp class=selectedgtHello Againltpgt ltdivgtltspangtAnd Againltspangtltdivgt

        find

        Get the descendants of each element in the current set of matched elements f iltered by aselector jQuery object or element

        Added in version 16

        f ind(element)jQuery

        elementElement An element to match elements against

        Given a jQuery object that represents a set of DOM elements the f ind() method allows us tosearch through the descendants of these elements in the DOM tree and construct a newjQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree

        The f irst signature for the f ind()method accepts a selector expression of the same type thatwe can pass to the $() funct ion The elements will be f iltered by test ing whether they match thisselector

        Consider a page with a basic nested list on it

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        If we begin at item II we can f ind list items within it

        $( l i item-ii )find( l i )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 IImatches the selector expression it is not included in the results only descendants areconsidered candidates for the match

        Unlike in the rest of the tree traversal methods the selector expression is requiredin a call to find() If we need to retrieve all of the descendant elements we canpass in the universal selector to accomplish this

        Selector context is implemented with the f ind() method therefore $(liitem-ii)f ind(li) isequivalent to $(li liitem-ii)

        As of jQuery 16 we can also f ilter the select ion with a given jQuery collect ion or element Withthe same nested list as above if we start with

        var $allListElements = $( l i )

        And then pass this jQuery object to f ind

        $( l i item-ii )find( $allListElements )

        This will return a jQuery collect ion which contains only the list elements that are descendantsof item II

        Similarly an element may also be passed to f ind

        var item1 = $( l i item-1)[0]$( l i item-ii )find( item1 )css(background-color red)

        The result of this call would be a red background on item 1

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

        Javascript

        $(p)find(span)css(color red)

        HTML

        ltpgtltspangtHelloltspangt how are youltpgtltpgtMe Im ltspangtgoodltspangtltpgt

        Example 2 A select ion using a jQuery collect ion of all span tags Only spans within p tags arechanged to red while others are lef t blue

        CSS

        span color blue

        Javascript

        var $spans = $(span) $(p)find( $spans )css(color red)

        HTML

        ltpgtltspangtHelloltspangt how are youltpgt ltpgtMe Im ltspangtgoodltspangtltpgt ltdivgtDid you ltspangteatltspangt yetltdivgt

        Example 3 Add spans around each word then add a hover and italicize words with the let ter t

        Javascript

        var newText = $(p)text()split( )join(ltspangt ltspangt) newText = ltspangt + newText + ltspangt

        $(p)html( newText ) find(span) hover(function() $(this)addClass(hil ite) function() $(this)removeClass(hil ite) ) end() find(contains(t)) css(font-style ital ic font-weightbolder)

        CSS

        p font-size20px width200px cursordefault colorblue font-weightbold margin0 10px hi l ite backgroundyellow

        HTML

        ltpgt When the day is short find that which matters to you or stop believing ltpgt

        contents

        Get the children of each element in the set of matched elements including text and commentnodes

        Added in version 12

        contents()jQuery

        Given a jQuery object that represents a set of DOM elements the contents() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The contents() and children() methods aresimilar except that the former includes text nodes as well as HTML elements in the result ingjQuery object

        The contents() method can also be used to get the content document of an if rame if theif rame is on the same domain as the main page

        Consider a simple ltdivgt with a number of text nodes each of which is separated by two linebreak elements (ltbr gt)

        ltdiv class=containergt Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ltbr gtltbr gt Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut al iquip ex ea commodo consequat ltbr gt ltbr gt Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariaturltdivgt

        We can employ the contents() method to help convert this blob of text into three well-formedparagraphs

        $(container)contents()fi lter(function() return thisnodeType == 3) wrap(ltpgtltpgt)end()fi lter(br) remove()

        This code f irst retrieves the contents of ltdiv class=containergt and then f ilters it for textnodes which are wrapped in paragraph tags This is accomplished by test ing the nodeTypeproperty of the element This DOM property holds a numeric code indicat ing the nodes typetext nodes use the code 3 The contents are again f iltered this t ime for ltbr gt elements andthese elements are removed

        Example 1 Find all the text nodes inside a paragraph and wrap them with a bold tag

        Javascript

        $(p)contents()fi lter(function() return thisnodeType = 1 )wrap(ltbgt)

        HTML

        ltpgtHello lta href=httpejohnorggtJohnltagt how are you doingltpgt

        Example 2 Change the background colour of links inside of an if rame

        Javascript

        $(frameDemo)contents()find(a)css(background-colorBADA55)

        HTML

        ltiframe src=httpapijquerycom width=80 height=600 id=frameDemogtltiframegt

        closest

        Get the f irst ancestor element that matches the selector beginning at the current element andprogressing up through the DOM tree

        Added in version 16

        closest(element)jQuery

        elementElement An element to match elements against

        Given a jQuery object that represents a set of DOM elements the closest() method allows usto search through these elements and their ancestors in the DOM tree and construct a newjQuery object f rom the matching elements The parents() and closest() methods are similar inthat they both t raverse up the DOM tree The dif ferences between the two though subt le aresignif icant

        closest() parents()

        Begins with thecurrent element

        Begins with the parent element

        Travels up the DOMtree unt il it f inds amatch for the suppliedselector

        Travels up the DOM tree to the document s root elementadding each ancestor element to a temporary collect ion it thenf ilters that collect ion based on a selector if one is supplied

        The returned jQueryobject contains zeroor one element

        The returned jQuery object contains zero one or mult ipleelements

        ltul id=one class=level-1gt ltli class=item-igtIltl igt ltli id=ii class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        Suppose we perform a search for ltulgt elements start ing at item A

        $( l i item-a)closest(ul ) css(background-color red)

        This will change the color of the level-2 ltulgt since it is the f irst encountered when traveling upthe DOM tree

        Suppose we search for an ltligt element instead

        $( l i item-a)closest( l i ) css(background-color red)

        This will change the color of list item A The closest() method begins its search with theelement itself before progressing up the DOM tree and stops when item A matches theselector

        We can pass in a DOM element as the context within which to search for the closest element

        var l istItemII = documentgetElementById( i i )$( l i item-a)closest(ul l istItemII) css(background-color red)$( l i item-a)closest(one l istItemII) css(background-color green)

        This will change the color of the level-2 ltulgt because it is both the f irst ltulgt ancestor of listitem A and a descendant of list item II It will not change the color of the level-1 ltulgt howeverbecause it is not a descendant of list item II

        Example 1 Show how event delegat ion can be done with closest The closest list elementtoggles a yellow background when it or its descendent is clicked

        Javascript

        $( document )bind(click function( e ) $( etarget )closest(l i)toggleClass(hil ight) )

        CSS

        l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

        HTML

        ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

        Example 2 Pass a jQuery object to closest The closest list element toggles a yellowbackground when it or its descendent is clicked

        Javascript

        var $listElements = $(l i)css(color blue) $( document )bind(click function( e ) $( etarget )closest( $listElements )toggleClass(hil ight) )

        CSS

        l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow

        HTML

        ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt

        closest

        Gets an array of all the elements and selectors matched against the current element upthrough the DOM tree

        Added in version 14

        closest(selectors context)Array

        selectorsArray An array or string containing a selector expression to match elementsagainst (can also be a jQuery object)

        context Element (opt ional) A DOM element within which a matching element may befound If no context is passed in then the context of the jQuery setwill be used instead

        This method is primarily meant to be used internally or by plugin authors

        Example 1 Show how event delegat ion can be done with closest

        Javascript

        var close = $(l i first)closest([ul body]) $each(close function(i) $(l i)eq(i)html( thisselector + + thiselemnodeName ) )

        CSS

        HTML

        ltulgtltligtltligtltligtltligtltulgt

        children

        Get the children of each element in the set of matched elements opt ionally f iltered by aselector

        Added in version 10

        children(selector)jQuery

        selectorSelector (opt ional) A string containing a selector expression to matchelements against

        Given a jQuery object that represents a set of DOM elements the children() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree Note also that like mostjQuery methods children() does not return text nodes to get all children including text andcomment nodes use contents()

        The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it

        Consider a page with a basic nested list on it

        ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt

        If we begin at the level-2 list we can f ind its children

        $(ullevel-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 aselector expression all of the children are part of the returned jQuery object If we had suppliedone only the matching items among these three would be included

        Example 1 Find all children of the clicked element

        Javascript

        $(container)cl ick(function (e) $()removeClass(hil ite) var $kids = $(etarget)children() var len = $kidsaddClass(hil ite)length

        $(results spanfirst)text(len) $(results spanlast)text(etargettagName)

        epreventDefault() return false )

        CSS

        body font-size16px font-weightbolder div width130px height82px margin10px floatleft border1px solid blue padding4px container widthauto height105px margin0 floatnone bordernone hi l ite border-colorred results displayblock colorred p margin10px border1px solid transparent span colorblue border1px solid transparent input width100px em border1px solid transparent a border1px solid transparent b border1px solid transparent button border1px solid transparent

        HTML

        ltdiv id=containergt

        ltdivgt ltpgtThis ltspangtis the ltemgtwayltemgt weltspangt write ltemgttheltemgt demoltpgt

        ltdivgt ltdivgt lta href=gtltbgtwltbgtritltbgteltbgtltagt the ltspangtdemoltspangt ltbuttongtwrite theltbuttongt demo ltdivgt

        ltdivgt This ltspangtthe way we ltemgtwriteltemgt the ltemgtdemoltemgt soltspangt

        ltinput type=text value=early gt in ltdivgt ltpgt ltspangttltspangthe ltspangtmltspangtorning ltspan id=resultsgtFound ltspangt0ltspangt children in ltspangtTAGltspangtltspangt

        ltpgt ltdivgt

        Example 2 Find all children of each div

        Javascript

        $(div)children()css(border-bottom 3px double red)

        CSS

        body font-size16px font-weightbolder span colorblue p margin5px 0

        HTML

        ltpgtHello (this is a paragraph)ltpgt

        ltdivgtltspangtHello Again (this span is a child of the a div)ltspangtltdivgt ltpgtAnd ltspangtAgainltspangt (in another paragraph)ltpgt

        ltdivgtAnd One Last ltspangtTimeltspangt (most text directly in a div)ltdivgt

        Example 3 Find all children with a class selected of each div

        Javascript

        $(div)children(selected)css(color blue)

        CSS

        body font-size16px font-weightbolder p margin5px 0

        HTML

        ltdivgt ltspangtHelloltspangt ltp class=selectedgtHello Againltpgt ltdiv class=selectedgtAnd Againltdivgt

        ltpgtAnd One Last Timeltpgt ltdivgt

        add

        Add elements to the set of matched elements

        Added in version 14

        add(selector context)jQuery

        selectorSelector A string represent ing a selector expression to f ind addit ionalelements to add to the set of matched elements

        context Element The point in the document at which the selector should beginmatching similar to the context argument of the $(selector context)method

        Given a jQuery object that represents a set of DOM elements the add() method constructs anew jQuery object f rom the union of those elements and the ones passed into the methodThe argument to add() can be pret ty much anything that $() accepts including a jQueryselector 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 avariable for later use For example

        $(p)add(div)addClass(widget)var pdiv = $(p)add(div)

        The following will not save the added elements because the add() method creates a new setand leaves the original set in pdiv unchanged

        var pdiv = $(p)pdivadd(div) WRONG pdiv wil l not change

        Consider a page with a simple list and a paragraph following it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligtltulgtltpgta paragraphltpgt

        We can select the list items and then the paragraph by using either a selector or a reference tothe DOM element itself as the add() methods argument

        $( l i )add(p)css(background-color red)

        Or

        $( l i )add(documentgetElementsByTagName(p)[0]) css(background-color red)

        The result of this call is a red background behind all four elements Using an HTML snippet asthe add() methods argument (as in the third version) we can create addit ional elements on thef ly and add those elements to the matched set of elements Let s say for example that wewant to alter the background of the list items along with a newly created paragraph

        $( l i )add(ltp id=newgtnew paragraphltpgt) css(background-color red)

        Although the new paragraph has been created and its background color changed it st ill doesnot appear on the page To place it on the page we could add one of the insert ion methods tothe chain

        As of jQuery 14 the results f rom add() will always be returned in document order (rather than asimple concatenat ion)

        Note To reverse the add() you can use not( elements | selector ) to remove elements f rom thejQuery results or end() to return to the select ion before you added

        Example 1 Finds all divs and makes a border Then adds all paragraphs to the jQuery object toset their backgrounds yellow

        Javascript

        $(div)css(border 2px solid red) add(p) css(background yellow)

        CSS

        div width60px height60px margin10px floatleft p clearleft font-weightbold font-size16px colorblue margin0 10px padding2px

        HTML

        ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        ltpgtAdded this (notice no border)ltpgt

        Example 2 Adds more elements matched by the given expression to the set of matchedelements

        Javascript

        $(p)add(span)css(background yellow)

        HTML

        ltpgtHelloltpgtltspangtHello Againltspangt

        Example 3 Adds more elements created on the f ly to the set of matched elements

        Javascript

        $(p)clone()add(ltspangtAgainltspangt)appendTo(documentbody)

        HTML

        ltpgtHelloltpgt

        Example 4 Adds one or more Elements to the set of matched elements

        Javascript

        $(p)add(documentgetElementById(a))css(background yellow)

        HTML

        ltpgtHelloltpgtltspan id=agtHello Againltspangt

        Example 5 Demonstrates how to add (or push) elements to an exist ing collect ion

        Javascript

        var collection = $(p) capture the new collectioncollection = collectionadd(documentgetElementById(a))collectioncss(background yellow)

        HTML

        ltpgtHelloltpgtltspan id=agtHello Againltspangt

        not

        Remove elements f rom the set of matched elements

        Added in version 14

        not(funct ion(index))jQuery

        funct ion(index)Funct ion A funct ion used as a test for each element in the set this isthe current DOM element

        Given a jQuery object that represents a set of DOM elements the not() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element the elements that dont match the selector will be included in the result

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        We can apply this method to the set of list items

        $( l i )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 not() method allows us to remove elements f rom the matched setassuming we have found those elements previously by some other means For examplesuppose our list had an id applied to one of its items

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli id=notligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        We can fetch the third list item using the nat ive JavaScript getElementById() funct ion thenremove it f rom a jQuery object

        $( l i )not(documentgetElementById(notl i )) css(background-color red)

        This statement changes the color of items 1 2 4 and 5 We could have accomplished thesame thing with a simpler jQuery expression but this technique can be useful when forexample other libraries provide references to plain DOM nodes

        As of jQuery 14 the not() method can take a funct ion as its argument in the same way thatf ilter() does Elements for which the funct ion returns t rue are excluded from the f iltered set allother elements are included

        Example 1 Adds a border to divs that are not green or blue

        Javascript

        $(div)not(green blueone) css(border-color red)

        CSS

        div width50px height50px margin10px floatleft backgroundyellow border2px solid white green background8f8 gray backgroundccc blueone background99f

        HTML

        ltdivgtltdivgt ltdiv id=blueonegtltdivgt ltdivgtltdivgt ltdiv class=greengtltdivgt

        ltdiv class=greengtltdivgt ltdiv class=graygtltdivgt ltdivgtltdivgt

        Example 2 Removes the element with the ID selected f rom the set of all paragraphs

        Javascript

        $(p)not( $(selected)[0] )

        Example 3 Removes the element with the ID selected f rom the set of all paragraphs

        Javascript

        $(p)not(selected)

        Example 4 Removes all elements that match div pselected f rom the total set of allparagraphs

        Javascript

        $(p)not($(div pselected))

        map

        Pass each element in the current matched set through a funct ion producing a new jQueryobject containing the return values

        Added in version 12

        map(callback(index domElement))jQuery

        callback(indexdomElement)Funct ion

        A funct ion object that will be invoked for each element inthe current set

        As the return value is a jQuery-wrapped array it s very common to get() the returned object towork with a basic array

        The map() method is part icularly useful for gett ing or set t ing the value of a collect ion ofelements Consider a form with a set of checkboxes in it

        ltform method=post action=gt ltfieldsetgt ltdivgt ltlabel for=twogt2ltlabelgt ltinput type=checkbox value=2 id=two name=number[]gt ltdivgt ltdivgt ltlabel for=fourgt4ltlabelgt ltinput type=checkbox value=4 id=four name=number[]gt ltdivgt ltdivgt ltlabel for=sixgt6ltlabelgt ltinput type=checkbox value=6 id=six name=number[]gt ltdivgt ltdivgt ltlabel for=eightgt8ltlabelgt ltinput type=checkbox value=8 id=eight name=number[]gt ltdivgt ltfieldsetgtltformgt

        We can get a comma-separated list of checkbox IDs

        $(checkbox)map(function() return thisid)get()join( )

        The result of this call is the string twofoursixeight

        Within the callback funct ion this refers to the current DOM element for each iterat ion Thefunct ion can return an individual data item or an array of data items to be inserted into theresult ing set If an array is returned the elements inside the array are inserted into the set If thefunct ion returns null or undef ined no element will be inserted

        Example 1 Build a list of all the values within a form

        Javascript

        $(p)append( $(input)map(function() return $(this)val() )get()join( ) )

        CSS

        p colorred

        HTML

        ltpgtltbgtValues ltbgtltpgt ltformgt ltinput type=text name=name value=Johngt

        ltinput type=text name=password value=passwordgt ltinput type=text name=url value=httpejohnorggt

        ltformgt

        Example 2 A contrived example to show some funct ionality

        Javascript

        var mappedItems = $(l i)map(function (index) var replacement = $(ltligt)text($(this)text())get(0) i f (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$(ltligt)get(0)] $(replacement[0])append(ltbgt - Altbgt) $(replacement[1])append(Extra ltbgt - Bltbgt)

        replacement wil l be a dom element null or an array of dom elements return replacement)$(results)append(mappedItems)

        CSS

        body font-size16px ul floatleft margin0 30px colorblue results colorred

        HTML

        ltulgt ltligtFirstltl igt ltligtSecondltligt ltligtThirdltligt

        ltligtFourthltligt ltligtFifthltligt ltulgt ltul id=resultsgt

        ltulgt

        Example 3 Equalize the heights of the divs

        Javascript

        $fnequalizeHeights = function() var maxHeight = thismap(function(ie) return $(e)height() )get() return thisheight( Mathmaxapply(this maxHeight) )

        $( input)cl ick(function() $(div)equalizeHeights())

        CSS

        div width 40px floatleft input clearleft

        HTML

        ltinput type=button value=equalize div heightsgt

        ltdiv style=backgroundred height 40px gtltdivgtltdiv style=backgroundgreen height 70pxgtltdivgtltdiv style=backgroundblue height 50px gtltdivgt

        is

        Check the current matched set of elements against a selector element or jQuery object andreturn t rue if at least one of these elements matches the given arguments

        Added in version 16

        is(element)Boolean

        elementElement An element to match the current set of elements against

        Unlike other f iltering methods is() does not create a new jQuery object Instead it allows youto test the contents of a jQuery object without modif icat ion This is of ten useful insidecallbacks such as event handlers

        Suppose you have a list with two of its items containing a child element

        ltulgt ltligtlist ltstronggtitem 1ltstronggtltligt ltligtltspangtlist item 2ltspangtltligt ltligtlist item 3ltligtltulgt

        You can at tach a click handler to the ltulgt element and then limit the code to be triggered onlywhen a list item itself not one of its children is clicked

        $(ul)cl ick(function(event) var $target = $(eventtarget) i f ( $targetis( l i) ) $targetcss(background-color red) )

        Now when the user clicks on the word list in the f irst item or anywhere in the third item theclicked list item will be given a red background However when the user clicks on item 1 in thef irst item or anywhere in the second item nothing will occur because in those cases the targetof the event would be ltstronggt or ltspangt respect ively

        Be aware that for selector strings with posit ional selectors such as f irst gt() or even theposit ional f iltering is done against the jQuery object passed to is() not against the containingdocument So for the HTML shown above an expression such as $(lif irst)is(lilast) returnstrue but $(lif irst-child)is(lilast-child) returns false

        Using a Function

        The second form of this method evaluates expressions related to elements based on afunct ion rather than a selector For each element if the funct ion returns t rue is() returns t rueas well For example given a somewhat more involved HTML snippet

        ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt

        You can at tach a click handler to every ltligt that evaluates the number of ltstronggt elementswithin the clicked ltligt at that t ime like so

        $(l i)cl ick(function() var $li = $(this) isWithTwo = $liis(function() return $(strong this)length === 2 ) i f ( isWithTwo ) $l i css(background-color green) else $l i css(background-color red) )

        Example 1 Shows a few ways is() can be used inside an event handler

        Javascript

        $(div)one(cl ick function () i f ($(this)is(first-child)) $(p)text(Its the first div) else if ($(this)is(bluered)) $(p)text(Its a blue or red div) else if ($(this)is(contains(Peter))) $(p)text(Its Peter) else $(p)html(Its nothing ltemgtspecialltemgt) $(p)hide()sl ideDown(slow) $(this)css(border-style inset cursordefault) )

        CSS

        div width60px height60px margin5px floatleft border4px outset backgroundgreen text-aligncenter font-weightbolder cursorpointer blue backgroundblue red backgroundred span colorwhite font-size16px p colorred font-weightbolder backgroundyellow margin3px clearleft displaynone

        HTML

        ltdivgtltdivgtltdiv class=bluegtltdivgtltdivgtltdivgtltdiv class=redgtltdivgt

        ltdivgtltbrgtltspangtPeterltspangtltdivgtltdiv class=bluegtltdivgtltpgtampnbspltpgt

        Example 2 Returns t rue because the parent of the input is a form element

        Javascript

        var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

        CSS

        div colorred

        HTML

        ltformgtltinput type=checkbox gtltformgtltdivgtltdivgt

        Example 3 Returns false because the parent of the input is a p element

        Javascript

        var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)

        CSS

        div colorred

        HTML

        ltformgtltpgtltinput type=checkbox gtltpgtltformgt ltdivgtltdivgt

        Example 4 Checks against an exist ing collect ion of alternat ing list elements Blue alternat inglist elements slide up while others turn red

        Javascript

        var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() var $li = $(this) i f ( $l i is( $alt ) ) $l i sl ideUp() else $l i css(background red) )

        CSS

        l i cursorpointer

        HTML

        ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

        Example 5 An alternate way to achieve the above example using an element rather than ajQuery object Checks against an exist ing collect ion of alternat ing list elements Bluealternat ing list elements slide up while others turn red

        Javascript

        var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() i f ( $altis( this ) ) $(this)sl ideUp() else $(this)css(background red) )

        CSS

        l i cursorpointer

        HTML

        ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt

        eq

        Reduce the set of matched elements to the one at the specif ied index

        Added in version 14

        eq(-index)jQuery

        -indexInteger

        An integer indicat ing the posit ion of the element count ing backwardsfrom the last element in the set

        Given a jQuery object that represents a set of DOM elements the eq() method constructs anew jQuery object f rom one element within that set The supplied index ident if ies the posit ionof this element in the set

        Consider a page with a simple list on it

        ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltulgt

        We can apply this method to the set of list items

        $( l i )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-basedand refers to the posit ion of the element within the jQuery object not within the DOM tree

        Providing a negat ive number indicates a posit ion start ing f rom the end of the set rather thanthe beginning For example

        $( l i )eq(-2)css(background-color red)

        This t ime list item 4 is turned red since it is two from the end of the set

        If an element cannot be found at the specif ied zero-based index the method constructs a newjQuery object with an empty set and a length property of 0

        $( l i )eq(5)css(background-color red)

        Here none of the list items is turned red since eq(5) indicates the sixth of f ive list items

        Example 1 Turn the div with index 2 blue by adding an appropriate class

        Javascript

        $(body)find(div)eq(2)addClass(blue)

        CSS

        div width60px height60px margin10px floatleft border2px solid blue blue backgroundblue

        HTML

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        filter

        Reduce the set of matched elements to those that match the selector or pass the funct ionstest

        Added in version 14

        f ilter(jQuery object)jQuery

        jQueryobject Object

        An exist ing jQuery object to match the current set of elementsagainst

        Given a jQuery object that represents a set of DOM elements the f ilter() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is tested

        new jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element all elements matching the selector will be included in the result

        Consider a page with a simple list on it

        list item 1

        list item 2

        list item 3

        list item 4

        list item 5

        list item 6

        We can apply this method to the set of list items

        $( l i )fi lter( 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 even and odd use 0-based indexing)

        Using a Filter Function

        The second form of this method allows us to f ilter elements against a funct ion rather than aselector For each element if the funct ion returns t rue (or a t ruthy value) the element will beincluded in the f iltered set otherwise it will be excluded Suppose we have a somewhat moreinvolved HTML snippet

        ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltligtlist item 6ltligtltulgt

        We can select the list items then f ilter them based on their contents

        $( l i )fi lter(function(index) return $(strong this)length == 1)css(background-color red)

        This code will alter the f irst list item only as it contains exact ly one ltstronggt tag Within the

        f ilter funct ion this refers to each DOM element in turn The parameter passed to the funct iontells us the index of that DOM element within the set matched by the jQuery object

        We can also take advantage of the index passed through the funct ion which indicates the 0-based posit ion of the element within the unf iltered set of matched elements

        $( l i )fi lter(function(index) return index 3 == 2)css(background-color red)

        This alterat ion to the code will cause the third and sixth list items to be highlighted as it usesthe modulus operator () to select every item with an index value that when divided by 3 hasa remainder of 2

        Example 1 Change the color of all divs then add a border to those with a middle class

        Javascript

        $(div)css(background c8ebcc) fi lter(middle) css(border-color red)

        CSS

        div width60px height60px margin5px floatleft border2px white solid

        HTML

        ltdivgtltdivgt

        ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt

        ltdivgtltdivgt

        Example 2 Change the color of all divs then add a border to the second one (index == 1) andthe div with an id of fourth

        Javascript

        $(div)css(background b4b0da) fi lter(function (index) return index == 1 || $(this)attr( id) == fourth ) css(border 3px double red)

        CSS

        div width60px height60px margin5px floatleft border3px white solid

        HTML

        ltdiv id=firstgtltdivgt ltdiv id=secondgtltdivgt ltdiv id=thirdgtltdivgt

        ltdiv id=fourthgtltdivgt ltdiv id=fifthgtltdivgt ltdiv id=sixthgtltdivgt

        Example 3 Select all divs and f ilter the select ion with a DOM element keeping only the one withan id of unique

        Javascript

        $(div)fi lter( documentgetElementById(unique) )

        Example 4 Select all divs and f ilter the select ion with a jQuery object keeping only the one withan id of unique

        Javascript

        $(div)fi lter( $(unique) )

        Attributes

        removeProp

        Remove a property for the set of matched elements

        Added in version 16

        removeProp(propertyName)jQuery

        propertyNameString The name of the property to set

        The removeProp() method removes propert ies set by the prop() method

        With some built -in propert ies of a DOM element or window object browsers may generate anerror if an at tempt is made to remove the property jQuery f irst assigns the value undef ined tothe property and ignores any error the browser generates In general it is only necessary toremove custom propert ies that have been set on an object and not built -in (nat ive) propert ies

        Note Do not use this method to remove nat ive propert ies such as checked disabled orselected This will remove the property completely and once removed cannot be added againto element Use prop() to set these propert ies to false instead

        Example 1 Set a numeric property on a paragraph and then remove it

        Javascript

        var $para = $(p)$paraprop(luggageCode 1234)$paraappend(The secret luggage code is String($paraprop(luggageCode)) )$pararemoveProp(luggageCode)$paraappend(Now the secret luggage code is String($paraprop(luggageCode)) )

        CSS

        img padding10px div colorred font-size24px

        HTML

        ltpgtltpgt

        prop

        Get the value of a property for the f irst element in the set of matched elements

        Added in version 16

        prop(propertyName)String

        propertyNameString The name of the property to get

        The prop() method gets the property value for only the first element in the matched set Itreturns undef ined for the value of a property that has not been set or if the matched set hasno elements To get the value for each element individually use a looping construct such asjQuerys each() or map() method

        The dif ference between attributes and properties can be important in specif ic situat ions BeforejQuery 16 the at t r() method sometimes took property values into account when retrievingsome attributes which could cause inconsistent behavior As of jQuery 16 the prop() methodprovides a way to explicit ly retrieve property values while at t r() retrieves at t ributes

        For example selectedIndex tagName nodeName nodeType ownerDocumentdefaultChecked and defaultSelected should be retrieved and set with the prop() method Priorto jQuery 16 these propert ies were retrievable with the at t r() method but this was not withinthe scope of at t r These do not have corresponding at t ributes and are only propert ies

        Concerning boolean at t ributes consider a DOM element def ined by the HTML markup ltinputtype=checkbox checked=checked gt and assume it is in a JavaScript variable named elem

        elemchecked t rue (Boolean) Will change with checkbox state

        $(elem)prop(checked) t rue (Boolean) Will change with checkbox state

        elemgetAttribute(checked)checked (String) Init ial state of the checkbox doesnot change

        $(elem)attr(checked)(16)checked (String) Init ial state of the checkbox doesnot change

        $(elem)attr(checked)(161+) checked (String) Will change with checkbox state

        $(elem)attr(checked)(pre-16)

        t rue (Boolean) Changed with checkbox state

        According to the W3C forms specif icat ion the checked at t ribute is a boolean attribute whichmeans the corresponding property is t rue if the at t ribute is present at allacirceurordquoeven if for examplethe at t ribute has no value or an empty string value The preferred cross-browser-compat ibleway to determine if a checkbox is checked is to check for a t ruthy value on the element sproperty using one of the following

        if ( elemchecked )

        if ( $(elem)prop(checked) )

        if ( $(elem)is(checked) )

        If using jQuery 16 the code if ( $(elem)at t r(checked) ) will retrieve the actual content attributewhich does not change as the checkbox is checked and unchecked It is meant only to storethe default or init ial value of the checked property To maintain backwards compatability theat t r() method in jQuery 161+ will retrieve and update the property for you so no code forboolean at t ributes is required to be changed to prop() Nevertheless the preferred way toretrieve a checked value is with one of the opt ions listed above To see how this works in thelatest jQuery checkuncheck the checkbox in the example below

        Example 1 Display the checked property and at t ribute of a checkbox as it changes

        Javascript

        $(input)change(function() var $input = $(this) $(p)html(attr(checked) ltbgt + $inputattr(checked) + ltbgtltbrgt + prop(checked) ltbgt + $inputprop(checked) + ltbgtltbrgt + is( checked) ltbgt + $inputis( checked) ) + ltbgt)change()

        CSS

        p margin 20px 0 0 b color blue

        HTML

        ltinput id=check1 type=checkbox checked=checkedgtltlabel for=check1gtCheck meltlabelgtltpgtltpgt

        prop

        Set one or more propert ies for the set of matched elements

        Added in version 16

        prop(propertyName funct ion(index oldPropertyValue))jQuery

        propertyNameString The name of the property to set

        funct ion(indexoldPropertyValue)Funct ion

        A funct ion returning the value to set Receives the indexposit ion of the element in the set and the old propertyvalue as arguments Within the funct ion the keyword thisrefers to the current element

        The prop() method is a convenient way to set the value of propert iesacirceurordquoespecially whensett ing mult iple propert ies using values returned by a funct ion or set t ing values on mult ipleelements at once It should be used when sett ing selectedIndex tagName nodeNamenodeType ownerDocument defaultChecked or defaultSelected Since jQuery 16 thesepropert ies can no longer be set with the at t r() method They do not have correspondingattributes and are only propert ies

        Propert ies generally af fect the dynamic state of a DOM element without changing theserialized HTML attribute Examples include the value property of input elements the disabledproperty of inputs and buttons or the checked property of a checkbox The prop() methodshould be used to set disabled and checked instead of the at t r() method The val() methodshould be used for gett ing and sett ing value

        $(input)prop(disabled false)$(input)prop(checked true)$(input)val(someValue)

        Important the removeProp() method should not be used to set these propert ies to false Oncea nat ive property is removed it cannot be added again See removeProp() for moreinformat ion

        Computed property values

        By using a funct ion to set propert ies you can compute the value based on other propert ies ofthe element For example to toggle all checkboxes based of f their individual values

        $(input[type=checkbox])prop(checked function( i val ) return val)

        Note If nothing is returned in the setter funct ion (ie funct ion(index prop)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

        Example 1 Disable all checkboxes on the page

        Javascript

        $(input[type=checkbox])prop( disabled true)

        CSS

        img padding10px div colorred font-size24px

        HTML

        ltinput type=checkbox checked=checked gt ltinput type=checkbox gt ltinput type=checkbox gt ltinput type=checkbox checked=checked gt

        val

        Get the current value of the f irst element in the set of matched elements

        Added in version 10

        val()String Number Array

        The val() method is primarily used to get the values of form elements In the case of ltselectmult iple=mult iplegt elements the val() method returns an array containing each selectedopt ion

        For selects and checkboxes you can also use the selected and checked selectors to get atvalues for example

        $(selectfoo optionselected)val() get the value from a dropdown select$(selectfoo)val() get the value from a dropdown select even easier$( inputcheckboxchecked)val() get the value from a checked checkbox$( inputradio[name=bar]checked)val() get the value from a set of radio buttons

        Example 1 Get the single value from a single select and an array of values from a mult ipleselect and display their values

        Javascript

        function displayVals() var singleValues = $(single)val() var multipleValues = $(multiple)val() || [] $(p)html(ltbgtSingleltbgt + singleValues + ltbgtMultipleltbgt + multipleValuesjoin( ))

        $(select)change(displayVals) displayVals()

        CSS

        p colorred margin4px b colorblue

        HTML

        ltpgtltpgt ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

        ltselectgt ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

        ltoption selected=selectedgtMultiple3ltoptiongt ltselectgt

        Example 2 Find the value of an input box

        Javascript

        $(input)keyup(function () var value = $(this)val() $(p)text(value) )keyup()

        CSS

        p colorblue margin8px

        HTML

        ltinput type=text value=some textgt ltpgtltpgt

        val

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

        Added in version 14

        val(funct ion(index value))jQuery

        funct ion(indexvalue)Funct ion

        A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the old valueas arguments

        This method is typically used to set the values of form f ields

        Passing an array of element values allows matching ltinput type=checkboxgt ltinputtype=radiogt and ltopt iongts inside of n ltselect mult iple=mult iplegt to be selected In the caseof ltinput type=radiogts that are part of a radio group and ltselect mult iple=mult iplegt theother elements will be deselected

        The val() method allows us to set the value by passing in a funct ion As of jQuery 14 thefunct ion is passed two arguments the current element s index and its current value

        $( inputtextitems)val(function(index value) return value + + thisclassName)

        This example appends the string items to the text inputs values

        Example 1 Set the value of an input box

        Javascript

        $(button)cl ick(function () var text = $(this)text() $(input)val(text) )

        CSS

        button margin4px cursorpointer input margin4px colorblue

        HTML

        ltdivgt ltbuttongtFeedltbuttongt ltbuttongttheltbuttongt

        ltbuttongtInputltbuttongt ltdivgt ltinput type=text value=click a button gt

        Example 2 Use the funct ion argument to modify the value of an input box

        Javascript

        $( input)bind(blur function() $(this)val(function(i val) return valtoUpperCase() ) )

        HTML

        ltpgtType something and then click or tab out of the inputltpgt ltinput type=text value=type something gt

        Example 3 Set a single select a mult iple select checkboxes and a radio button

        Javascript

        $(single)val(Single2) $(multiple)val([Multiple2 Multiple3]) $(input)val([check1check2 radio1 ])

        CSS

        body colorblue

        HTML

        ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

        ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

        ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=checkboxname value=check1gt check1 ltinput type=checkbox name=checkboxname value=check2gt check2 ltinput type=radio name=r value=radio1gt radio1 ltinput type=radio name=r value=radio2gt radio2

        html

        Get the HTML contents of the f irst element in the set of matched elements

        Added in version 10

        html()String

        This method is not available on XML documents

        In an HTML document html() can be used to get the contents of any element If the selectorexpression matches more than one element only the f irst match will have its HTML contentreturned Consider this code

        $(divdemo-container)html()

        In order for the following ltdivgts content to be retrieved it would have to be the f irst one withclass=demo-container in the document

        ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

        The result would look like this

        ltdiv class=demo-boxgtDemonstration Boxltdivgt

        This method uses the browsers innerHTML property Some browsers may not return HTML

        that exact ly replicates the HTML source in an original document For example Internet Explorersometimes leaves of f the quotes around at t ribute values if they contain only alphanumericcharacters

        Example 1 Click a paragraph to convert it f rom html to text

        Javascript

        $(p)cl ick(function () var htmlStr = $(this)html() $(this)text(htmlStr) )

        CSS

        p margin8px font-size20px colorblue cursorpointer b text-decorationunderline button cursorpointer

        HTML

        ltpgt

        ltbgtClickltbgt to change the ltspan id=taggthtmlltspangt ltpgt ltpgt

        to a ltspan id=textgttextltspangt node ltpgt ltpgt This ltbutton name=nadagtbuttonltbuttongt does nothing ltpgt

        html

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

        Added in version 14

        html(funct ion(index oldhtml))jQuery

        funct ion(indexoldhtml)Funct ion

        A funct ion returning the HTML content to set Receives the indexposit ion of the element in the set and the old HTML value asarguments jQuery empt ies the element before calling the funct ionuse the oldhtml argument to reference the previous content Withinthe funct ion this refers to the current element in the set

        The html() method is not available in XML documents

        When html() is used to set an element s content any content that was in that element iscompletely replaced by the new content Consider the following HTML

        ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt

        The content of ltdiv class=demo-containergt can be set like this

        $(divdemo-container) html(ltpgtAll new content ltemgtYou betltemgtltpgt)

        That line of code will replace everything inside ltdiv class=demo-containergt

        ltdiv class=demo-containergt ltpgtAll new content ltemgtYou betltemgtltpgtltdivgt

        As of jQuery 14 the html() method allows the HTML content to be set by passing in afunct ion

        $(divdemo-container)html(function() var emph = ltemgt + $(p)length + paragraphsltemgt return ltpgtAll new content for + emph + ltpgt)

        Given a document with six paragraphs this example will set the HTML of ltdiv class=demo-containergt to ltpgtAll new content for ltemgt6 paragraphsltemgtltpgt

        This method uses the browsers innerHTML property Some browsers may not generate a DOMthat exact ly replicates the HTML source provided For example Internet Explorer prior toversion 8 will convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer

        Example 1 Add some html to each div

        Javascript

        $(div)html(ltspan class=redgtHello ltbgtAgainltbgtltspangt)

        CSS

        red colorred

        HTML

        ltspangtHelloltspangt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        Example 2 Add some html to each div then immediately do further manipulat ions to theinserted html

        Javascript

        $(div)html(ltbgtWowltbgt Such excitement) $(div b)append(documentcreateTextNode()) css(color red)

        CSS

        div colorblue font-size18px

        HTML

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        toggleClass

        Add or remove one or more classes from each element in the set of matched elementsdepending on either the classs presence or the value of the switch argument

        Added in version 14

        toggleClass(funct ion(index class switch) switch)jQuery

        funct ion(indexclassswitch)Funct ion

        A funct ion that returns class names to be toggled in the classattribute of each element in the matched set Receives the indexposit ion of the element in the set the old class value and the switchas arguments

        switchBoolean (opt ional) A boolean value to determine whether the class should beadded or removed

        This method takes one or more class names as its parameter In the f irst version if an elementin the matched set of elements already has the class then it is removed if an element does nothave the class then it is added For example we can apply toggleClass() to a simple ltdivgt

        ltdiv class=tumblegtSome textltdivgt

        The f irst t ime we apply $(divtumble)toggleClass(bounce) we get the following

        ltdiv class=tumble bouncegtSome textltdivgt

        The second t ime we apply $(divtumble)toggleClass(bounce) the ltdivgt class is returned tothe single tumble value

        ltdiv class=tumblegtSome textltdivgt

        Applying toggleClass(bounce spin) to the same ltdivgt alternates between ltdiv class=tumblebounce spingt and ltdiv class=tumblegt

        The second version of toggleClass() uses the second parameter for determining whether theclass should be added or removed If this parameters value is t rue then the class is added iffalse the class is removed In essence the statement

        $(foo)toggleClass(className addOrRemove)

        is equivalent to

        i f (addOrRemove) $(foo)addClass(className) else $(foo)removeClass(className)

        As of jQuery 14 if no arguments are passed to toggleClass() all class names on the elementthe f irst t ime toggleClass() is called will be toggled Also as of jQuery 14 the class name to be

        toggled can be determined by passing in a funct ion

        $(divfoo)toggleClass(function() if ($(this)parent()is( bar)) return happy else return sad )

        This example will toggle the happy class for ltdiv class=foogt elements if their parent elementhas a class of bar otherwise it will toggle the sad class

        Example 1 Toggle the class highlight when a paragraph is clicked

        Javascript

        $(p)cl ick(function () $(this)toggleClass(highlight) )

        CSS

        p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundyellow

        HTML

        ltp class=bluegtClick to toggleltpgt ltp class=blue highlightgthighlightltpgt ltp class=bluegton theseltpgt ltp class=bluegtparagraphsltpgt

        Example 2 Add the highlight class to the clicked paragraph on every third click of thatparagraph remove it every f irst and second click

        Javascript

        var count = 0$(p)each(function() var $thisParagraph = $(this) var count = 0 $thisParagraphclick(function() count++ $thisParagraphfind(span)text(cl icks + count) $thisParagraphtoggleClass(highlight count 3 == 0) ))

        CSS

        p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundred

        HTML

        ltp class=bluegtClick to toggle (ltspangtclicks 0ltspangt)ltpgt ltp class=blue highlightgthighlight (ltspangtclicks 0ltspangt)ltpgt ltp class=bluegton these (ltspangtclicks 0ltspangt)ltpgt

        ltp class=bluegtparagraphs (ltspangtclicks 0ltspangt)ltpgt

        Example 3 Toggle the class name(s) indicated on the buttons for each div

        CSS

        wrap gt div float left width 100px margin 1em 1em 0 0 padding=left 3px border 1px solid abc diva background-color aqua divb background-color burlywood divc background-color cornsilk

        HTML

        ltdiv class=buttonsgt ltbuttongttoggleltbuttongt ltbutton class=agttoggle altbuttongt ltbutton class=a bgttoggle a bltbuttongt ltbutton class=a b cgttoggle a b cltbuttongt lta href=gtresetltagtltdivgtltdiv class=wrapgt ltdivgtltdivgt ltdiv class=bgtltdivgt ltdiv class=a bgtltdivgt ltdiv class=a cgtltdivgtltdivgt

        Javascript

        var cls = [ a a b a b c]var divs = $(divwrap)children()var appendClass = function() divsappend(function() return ltdivgt + (thisclassName || none) + ltdivgt )

        appendClass()

        $(button)bind(cl ick function() var tc = thisclassName || undefined divstoggleClass(tc) appendClass())

        $(a)bind(cl ick function(event) eventpreventDefault() divsempty()each(function(i) thisclassName = cls[i] ) appendClass())

        removeClass

        Remove a single class mult iple classes or all classes from each element in the set of matchedelements

        Added in version 14

        removeClass(funct ion(index class))jQuery

        funct ion(index A funct ion returning one or more space-separated class names to be

        class)Funct ion removed Receives the index posit ion of the element in the set and theold class value as arguments

        If a class name is included as a parameter then only that class will be removed from the set ofmatched elements If no class names are specif ied in the parameter all classes will be removed

        More than one class may be removed at a t ime separated by a space f rom the set of matchedelements like so

        $(p)removeClass(myClass yourClass)

        This method is of ten used with addClass() to switch elements classes from one to anotherlike so

        $(p)removeClass(myClass noClass)addClass(yourClass)

        Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

        To replace all exist ing classes with another class we can use at t r(class newClass) instead

        As of jQuery 14 the removeClass() method allows us to indicate the class to be removed bypassing in a funct ion

        $( l i last)removeClass(function() return $(this)prev()attr(class) )

        This example removes the class name of the penult imate ltligt f rom the last ltligt

        Example 1 Remove the class blue f rom the matched elements

        Javascript

        $(peven)removeClass(blue)

        CSS

        p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

        HTML

        ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

        ltp class=blue undergtGoodbyeltpgt

        Example 2 Remove the class blue and under f rom the matched elements

        Javascript

        $(podd)removeClass(blue under)

        CSS

        p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

        HTML

        ltp class=blue undergtHelloltpgt

        ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt ltp class=blue undergtGoodbyeltpgt

        Example 3 Remove all the classes from the matched elements

        Javascript

        $(peq(1))removeClass()

        CSS

        p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow

        HTML

        ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt

        ltp class=blue undergtGoodbyeltpgt

        hasClass

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

        Added in version 12

        hasClass(className)Boolean

        classNameString The class name to search for

        Elements may have more than one class assigned to them In HTML this is represented byseparat ing the class names with a space

        ltdiv id=mydiv class=foo bargtltdivgt

        The hasClass() method will return t rue if the class is assigned to an element even if otherclasses also are For example given the HTML above the following will return t rue

        $(mydiv)hasClass(foo)

        As would

        $(mydiv)hasClass(bar)

        While this would return false

        $(mydiv)hasClass(quux)

        Example 1 Looks for the paragraph that contains selected as a class

        Javascript

        $(divresult1)append($(pfirst)hasClass(selected)toString())$(divresult2)append($(plast)hasClass(selected)toString())$(divresult3)append($(p)hasClass(selected)toString())

        CSS

        p margin 8px font-size16px selected colorred

        HTML

        ltpgtThis paragraph is black and is the first paragraphltpgt ltp class=selectedgtThis paragraph is red and is the second paragraphltpgt

        ltdiv id=result1gtFirst paragraph has selected class ltdivgt ltdiv id=result2gtSecond paragraph has selected class ltdivgt ltdiv id=result3gtAt least one paragraph has selected class ltdivgt

        removeAttr

        Remove an at t ribute f rom each element in the set of matched elements

        Added in version 10

        removeAttr(at t ributeName)jQuery

        attributeNameString An at t ribute to remove

        The removeAttr() method uses the JavaScript removeAttribute() funct ion but it has theadvantage of being able to be called direct ly on a jQuery object and it accounts for dif ferentat t ribute naming across browsers

        NoteIf at tempt ing to remove an inline onclick event handler using removeAttr() one may f indthat this doesnt achieve the desired ef fect in Internet Explorer 67 or 8 Instead it isrecommended to opt for using prop() to achieve this as follows

        $elementprop(onclick null)consolelog(onclick property $element[0]onclick)

        We may update the behavior of removeAttr() at some point in the future to better handle thishowever for the t ime being the above should be considered the standard cross-browserapproach to this problem

        Example 1 Clicking the button enables the input next to it

        Javascript

        $(button)cl ick(function () $(this)next()removeAttr(disabled) focus() val(editable now))

        HTML

        ltbuttongtEnableltbuttongtltinput type=text disabled=disabled value=cant edit this gt

        attr

        Get the value of an at t ribute for the f irst element in the set of matched elements

        Added in version 10

        attr(at t ributeName)String

        attributeNameString The name of the at t ribute to get

        The at t r() method gets the at t ribute value for only the first element in the matched set To getthe value for each element individually use a looping construct such as jQuerys each() ormap() method

        As of jQuery 16 the at t r() method returns undef ined for at t ributes that have not been set Inaddit ion at t r() should not be used on plain objects arrays the window or the document Toretrieve and change DOM propert ies use the prop() method

        Using jQuerys at t r() method to get the value of an element s at t ribute has two main benef its

        1 Convenience It can be called direct ly on a jQuery object and chained to other jQuerymethods

        2 Cross-browser consistency The values of some attributes are reported inconsistent lyacross browsers and even across versions of a single browser The at t r() methodreduces such inconsistencies

        Note Attribute values are strings with the exception of a few attributes such asvalue and tabindex

        Example 1 Find the t it le at t ribute of the f irst in the page

        Javascript

        var title = $(em)attr(title) $(div)text(title)

        CSS

        em colorblue font-weightbold div colorred

        HTML

        ltpgt Once there was a ltem title=huge giganticgtlargeltemgt dinosaurltpgt

        The title of the emphasis isltdivgtltdivgt

        attr

        Set one or more at t ributes for the set of matched elements

        Added in version 11

        attr(at t ributeName funct ion(index at t r))jQuery

        attributeNameString The name of the at t ribute to set

        funct ion(indexat t r)Funct ion

        A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the oldattribute value as arguments

        The at t r() method is a convenient way to set the value of at t ributesacirceurordquoespecially when sett ingmult iple at t ributes or using values returned by a funct ion Consider the following image

        ltimg id=greatphoto src=brush-sellerjpg alt=brush seller gt

        Setting a simple attribute

        To change the alt at t ribute simply pass the name of the at t ribute and its new value to theat t r() method

        $(greatphoto)attr(alt Beij ing Brush Seller)

        Add an at t ribute the same way

        $(greatphoto)attr(title Photo by Kelly Clark)

        Setting several attributes at once

        To change the alt at t ribute and add the t it le at t ribute at the same t ime pass both sets ofnames and values into the method at once using a map (JavaScript object literal) Each key-value pair in the map adds or modif ies an at t ribute

        $(greatphoto)attr( alt Beij ing Brush Seller title photo by Kelly Clark)

        When sett ing mult iple at t ributes the quotes around at t ribute names are opt ional

        WARNING When sett ing the class at t ribute you must always use quotes

        Note jQuery prohibits changing the type at t ribute on an ltinputgt or ltbuttongt element and willthrow an error in all browsers This is because the type at t ribute cannot be changed in InternetExplorer

        Computed attribute values

        By using a funct ion to set at t ributes you can compute the value based on other propert ies ofthe element For example to concatenate a new value with an exist ing value

        $(greatphoto)attr(title function(i val) return val + - photo by Kelly Clark)

        This use of a funct ion to compute at t ribute values can be part icularly useful when modifyingthe at t ributes of mult iple elements at once

        Note If nothing is returned in the setter funct ion (ie funct ion(index at t r)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

        Example 1 Set some attributes for all s in the page

        Javascript

        $(img)attr( src imageshatgif title jQuery alt jQuery Logo)$(div)text($(img)attr(alt))

        CSS

        img padding10px div colorred font-size24px

        HTML

        ltimg gt ltimg gt ltimg gt

        ltdivgtltBgtAttribute of AjaxltBgtltdivgt

        Example 2 Disable buttons greater than the 1st button

        Javascript

        $(buttongt(1))attr(disableddisabled)

        CSS

        button margin10px

        HTML

        ltbuttongt0th Buttonltbuttongt ltbuttongt1st Buttonltbuttongt ltbuttongt2nd Buttonltbuttongt

        Example 3 Set the id for divs based on the posit ion in the page

        Javascript

        $(div)attr( id function (arr) return div-id + arr)each(function () $(span this)html((ID = ltbgt + thisid + ltbgt)))

        CSS

        div colorblue span colorred b font-weightbolder

        HTML

        ltdivgtZero-th ltspangtltspangtltdivgt ltdivgtFirst ltspangtltspangtltdivgt ltdivgtSecond ltspangtltspangtltdivgt

        Example 4 Set the src at t ribute f rom t it le at t ribute on the image

        Javascript

        $(img)attr(src function() return images + thistitle )

        HTML

        ltimg title=hatgifgt

        addClass

        Adds the specif ied class(es) to each of the set of matched elements

        Added in version 14

        addClass(funct ion(index currentClass))jQuery

        funct ion(indexcurrentClass)Funct ion

        A funct ion returning one or more space-separated class namesto be added to the exist ing class name(s) Receives the indexposit ion of the element in the set and the exist ing class name(s)as arguments Within the funct ion this refers to the currentelement in the set

        It s important to note that this method does not replace a class It simply adds the classappending it to any which may already be assigned to the elements

        More than one class may be added at a t ime separated by a space to the set of matchedelements like so

        $(p)addClass(myClass yourClass)

        This method is of ten used with removeClass() to switch elements classes from one toanother like so

        $(p)removeClass(myClass noClass)addClass(yourClass)

        Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded

        As of jQuery 14 the addClass() methods argument can receive a funct ion

        $(ul l i last)addClass(function() return item- + $(this)index())

        Given an unordered list with f ive ltligt elements this example adds the class item-4 to the lastltligt

        Example 1 Adds the class selected to the matched elements

        Javascript

        $(plast)addClass(selected)

        CSS

        p margin 8px font-size16px selected colorblue highlight backgroundyellow

        HTML

        ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

        Example 2 Adds the classes selected and highlight to the matched elements

        Javascript

        $(plast)addClass(selected highlight)

        CSS

        p margin 8px font-size16px selected colorred highlight backgroundyellow

        HTML

        ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt

        Example 3 Pass in a funct ion to addClass() to add the green class to a div that already has ared class

        Javascript

        $(div)addClass(function(index currentClass) var addedClass

        i f ( currentClass === red ) addedClass = green $(p)text(There is one green div) return addedClass )

        CSS

        div background white red background red redgreen background green

        HTML

        ltdivgtThis div should be whiteltdivgt ltdiv class=redgtThis div wil l be green because it now has the green and red classes It would be red if the addClass function failedltdivgt ltdivgtThis div should be whiteltdivgt ltpgtThere are zero green divsltpgt

        CSS

        jQuerycssHooks

        Hook direct ly into jQuery to override how part icular CSS propert ies are retrieved or set normalize CSS property naming or create custom propert ies

        Added in version 143

        The $cssHooks object provides a way to def ine funct ions for gett ing and sett ing part icularCSS values It can also be used to create new cssHooks for normalizing CSS3 features such asbox shadows and gradients

        For example some versions of Webkit -based browsers require -webkit -border-radius to set theborder-radius on an element while earlier Firefox versions require -moz-border-radius AcssHook can normalize these vendor-pref ixed propert ies to let css() accept a single standardproperty name (border-radius or with DOM property syntax borderRadius)

        In addit ion to providing f ine-grained control over how specif ic style propert ies are handled$cssHooks also extends the set of propert ies available to the animate() method

        Def ining a new cssHook is straight-forward The skeleton template below can serve as a guideto creat ing your own

        (function($) first check to see if cssHooks are supported if ( $cssHooks ) i f not output an error message throw(jQuery 143 or above is required for this plugin to work) return

        $cssHooks[someCSSProp] = get function( elem computed extra ) handle getting the CSS property set function( elem value ) handle setting the CSS value )(jQuery)

        Feature Testing

        Before normalizing a vendor-specif ic CSS property f irst determine whether the browsersupports the standard property or a vendor-pref ixed variat ion For example to check forsupport of the border-radius property see if any variat ion is a member of a temporary

        element s style object

        (function($) function styleSupport( prop ) var vendorProp supportedProp

        capitalize first character of the prop to test vendor prefix capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

        i f ( prop in divstyle )

        browser supports standard CSS property name supportedProp = prop else

        otherwise test support for vendor-prefixed property names for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

        avoid memory leak in IE div = null add property to $support so it can be accessed elsewhere $support[ prop ] = supportedProp return supportedProp

        call the function eg testing for border-radius support styleSupport( borderRadius ))(jQuery)

        Defining a complete cssHook

        To def ine a complete cssHook combine the support test with a f illed-out version of theskeleton template provided in the f irst example

        (function($) if ( $cssHooks ) throw(jQuery 143+ is needed for this plugin to work) return function styleSupport( prop ) var vendorProp supportedProp capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )

        i f ( prop in divstyle ) supportedProp = prop else for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break

        div = null $support[ prop ] = supportedProp return supportedProp

        var borderRadius = styleSupport( borderRadius )

        Set cssHooks only for browsers that support a vendor-prefixed border radius if ( borderRadius ampamp borderRadius == borderRadius ) $cssHookborderRadius = get function( elem computed extra ) return $css( elem borderRadius ) set function( elem value) elemstyle[ borderRadius ] = value )(jQuery)

        You can then set the border radius in a supported browser using either the DOM (camelCased)style or the CSS (hyphenated) style

        $(element)css(borderRadius 10px)$(another)css(border-radius 20px)

        If the browser lacks support for any form of the CSS property vendor-pref ixed or not the styleis not applied to the element However if the browser supports a proprietary alternat ive it canbe applied to the cssHooks instead

        (function($) feature test for support of a CSS property and a proprietary alternative

        i f ( $supportsomeCSSProp ampamp $supportsomeCSSProp == someCSSProp )

        Set cssHooks for browsers that support only a vendor-prefixed someCSSProp $cssHooksomeCSSProp = get function( elem computed extra ) return $css( elem $supportsomeCSSProp ) set function( elem value) elemstyle[ $supportsomeCSSProp ] = value else if ( supportsProprietaryAlternative ) $cssHooksomeCSSProp = get function( elem computed extra ) Handle crazy conversion from the proprietary alternative set function( elem value ) Handle crazy conversion to the proprietary alternative

        )(jQuery)

        Special units

        By default jQuery adds a px unit to the values passed to the css() method This behavior canbe prevented by adding the property to the jQuerycssNumber object

        $cssNumber[someCSSProp] = true

        Animating with cssHooks

        A cssHook can also hook into jQuerys animat ion mechanism by adding a property to thejQueryfxstep object

        $fxstep[someCSSProp] = function(fx) $cssHooks[someCSSProp]set( fxelem fxnow + fxunit )

        Note that this works best for simple numeric-value animat ions More custom code may berequired depending on the CSS property the type of value it returns and the animat ionscomplexity

        outerWidth

        Get the current computed width for the f irst element in the set of matched elements includingpadding and border

        Added in version 126

        outerWidth(includeMargin)Integer

        includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

        Returns the width of the element along with lef t and right padding border and opt ionallymargin in pixels

        If includeMargin is omit ted or false the padding and border are included in the calculat ion ift rue the margin is also included

        This method is not applicable to window and document objects for these use width() instead

        Example 1 Get the outerWidth of a paragraph

        Javascript

        var p = $(pfirst)$(plast)text( outerWidth + pouterWidth()+ outerWidth(true) + pouterWidth(true) )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        outerHeight

        Get the current computed height for the f irst element in the set of matched elements includingpadding border and opt ionally margin

        Added in version 126

        outerHeight(includeMargin)Integer

        includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion

        The top and bottom padding and border are always included in the outerHeight() calculat ion ifthe includeMargin argument is set to t rue the margin (top and bottom) is also included

        This method is not applicable to window and document objects for these use height() instead

        Example 1 Get the outerHeight of aparagraph

        Javascript

        var p = $(pfirst)$(plast)text( outerHeight + pouterHeight() + outerHeight(true) + pouterHeight(true) )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        innerWidth

        Get the current computed width for the f irst element in the set of matched elements includingpadding but not border

        Added in version 126

        innerWidth()Integer

        This method returns the width of the element including lef t and right padding in pixels

        This method is not applicable to window and document objects for these use width() instead

        Example 1 Get the innerWidth of a paragraph

        Javascript

        var p = $(pfirst)$(plast)text( innerWidth + pinnerWidth() )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        innerHeight

        Get the current computed height for the f irst element in the set of matched elements includingpadding but not border

        Added in version 126

        innerHeight()Integer

        This method returns the height of the element including top and bottom padding in pixels

        This method is not applicable to window and document objects for these use height() instead

        Example 1 Get the innerHeight of aparagraph

        Javascript

        var p = $(pfirst)$(plast)text( innerHeight + pinnerHeight() )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        width

        Get the current computed width for the f irst element in the set of matched elements

        Added in version 10

        width()Integer

        The dif ference between css(width) and width() is that the lat ter returns a unit -less pixel value(for example 400) while the former returns a value with units intact (for example 400px) Thewidth() method is recommended when an element s width needs to be used in a mathematicalcalculat ion

        This method is also able to f ind the width of thewindow and document

        $(window)width() returns width of browser viewport$(document)width() returns width of HTML document

        Note that width() will always return the content width regardless of the value of the CSS box-sizing property

        Example 1 Show various widths Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

        Javascript

        function showWidth(ele w) $(div)text(The width for the + ele + is + w + px) $(getp)cl ick(function () showWidth(paragraph $(p)width()) ) $(getd)cl ick(function () showWidth(document $(document)width()) ) $(getw)cl ick(function () showWidth(window $(window)width()) )

        CSS

        body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

        HTML

        ltbutton id=getpgtGet Paragraph Widthltbuttongt ltbutton id=getdgtGet Document Widthltbuttongt ltbutton id=getwgtGet Window Widthltbuttongt

        ltdivgtampnbspltdivgt ltpgt Sample paragraph to test width ltpgt

        width

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

        Added in version 141

        width(funct ion(index width))jQuery

        funct ion(indexwidth)Funct ion

        A funct ion returning the width to set Receives the index posit ion ofthe element in the set and the old width as arguments Within thefunct ion this refers to the current element in the set

        When calling width(value) the value can be either a string (number and unit ) or a number Ifonly 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 100px 50 or auto)Note that in modern browsers the CSS width property does not include padding border ormargin unless the box-sizing CSS property is used

        If no explicit unit was specif ied (like em or ) then px is concatenated to the value

        Note that width(value) sets the width of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterWidth of the box instead of the content width

        Example 1 To set the width of each div on click to 30px plus a color change

        Javascript

        $(div)one(cl ick function () $(this)width(30) css(cursorauto background-colorblue) )

        CSS

        div width70px height50px floatleft margin5px backgroundred cursorpointer

        HTML

        ltdivgtltdivgt ltdivgtdltdivgt

        ltdivgtdltdivgt ltdivgtdltdivgt ltdivgtdltdivgt

        height

        Get the current computed height for the f irst element in the set of matched elements

        Added in version 10

        height()Integer

        The dif ference between css(height ) and height() is that the lat ter returns a unit -less pixelvalue (for example 400) while the former returns a value with units intact (for example 400px)The height() method is recommended when an element s height needs to be used in amathematical calculat ion

        This method is also able to f ind the heightof the window and document

        $(window)height() returns height of browser viewport$(document)height() returns height of HTML document

        Note that height() will always return the content height regardless of the value of the CSSbox-sizing property

        Example 1 Show various heights Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body

        Javascript

        function showHeight(ele h) $(div)text(The height for the + ele + is + h + px) $(getp)cl ick(function () showHeight(paragraph $(p)height()) ) $(getd)cl ick(function () showHeight(document $(document)height()) ) $(getw)cl ick(function () showHeight(window $(window)height()) )

        CSS

        body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold

        HTML

        ltbutton id=getpgtGet Paragraph Heightltbuttongt ltbutton id=getdgtGet Document Heightltbuttongt ltbutton id=getwgtGet Window Heightltbuttongt

        ltdivgtampnbspltdivgt ltpgt Sample paragraph to test height ltpgt

        height

        Set the CSS height of every matched element

        Added in version 141

        height(funct ion(index height))jQuery

        funct ion(indexheight)Funct ion

        A funct ion returning the height to set Receives the index posit ion ofthe element in the set and the old height as arguments Within thefunct ion this refers to the current element in the set

        When calling height(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is providedhowever a valid CSS measurement must be provided for the height (such as 100px 50 orauto) Note that in modern browsers the CSS height property does not include paddingborder or margin

        If no explicit unit was specif ied (like em or ) then px is concatenated to the value

        Note that height(value) sets the height of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterHeight of the box instead of the content height

        Example 1 To set the height of each div on click to 30px plus a color change

        Javascript

        $(div)one(cl ick function () $(this)height(30) css(cursorauto backgroundColorgreen) )

        CSS

        div width50px height70px floatleft margin5px backgroundrgb(2551400) cursorpointer

        HTML

        ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        scrollLeft

        Get the current horizontal posit ion of the scroll bar for the f irst element in the set of matchedelements

        Added in version 126

        scrollLef t ()Integer

        The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area If the scroll bar is at the very lef t or if the element is not scrollablethis number will be 0

        Example 1 Get the scrollLef t of a paragraph

        Javascript

        var p = $(pfirst) $(plast)text( scrollLeft + pscrollLeft() )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        scrollLeft

        Set the current horizontal posit ion of the scroll bar for each of the set of matched elements

        Added in version 126

        scrollLef t (value)jQuery

        valueNumber An integer indicat ing the new posit ion to set the scroll bar to

        The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area Sett ing the scrollLef t posit ions the horizontal scroll of each matchedelement

        Example 1 Set the scrollLef t of a div

        Javascript

        $(divdemo)scrollLeft(300)

        CSS

        divdemo backgroundCCCCCC none repeat scroll 0 0 border3px solid 666666 margin5px padding5px positionrelative width200px height100px overflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

        HTML

        ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

        scrollTop

        Get the current vert ical posit ion of the scroll bar for the f irst element in the set of matchedelements

        Added in version 126

        scrollTop()Integer

        The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area If the scroll bar is at the very top or if the element is not scrollable thisnumber will be 0

        Example 1 Get the scrollTop of a paragraph

        Javascript

        var p = $(pfirst)$(plast)text( scrollTop + pscrollTop() )

        CSS

        p margin10pxpadding5pxborder2px solid 666

        HTML

        ltpgtHelloltpgtltpgtltpgt

        scrollTop

        Set the current vert ical posit ion of the scroll bar for each of the set of matched elements

        Added in version 126

        scrollTop(value)jQuery

        valueNumber An integer indicat ing the new posit ion to set the scroll bar to

        The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area Sett ing the scrollTop posit ions the vert ical scroll of each matched element

        Example 1 Set the scrollTop of a div

        Javascript

        $(divdemo)scrollTop(300)

        CSS

        divdemo backgroundCCCCCC none repeat scroll 0 0border3px solid 666666margin5pxpadding5pxpositionrelativewidth200pxheight100pxoverflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px

        HTML

        ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt

        position

        Get the current coordinates of the f irst element in the set of matched elements relat ive to theoffset parent

        Added in version 12

        posit ion()Object

        The posit ion() method allows us to retrieve the current posit ion of an element relative to theoffset parent Contrast this with of fset() which retrieves the current posit ion relative to thedocument When posit ioning a new element near another one and within the same containingDOM element posit ion() is the more useful

        Returns an object containing the propert ies top and lef t

        Example 1 Access the posit ion of the second paragraph

        Javascript

        var p = $(pfirst)var position = pposition()$(plast)text( left + positionleft + top + positiontop )

        CSS

        div padding 15px p margin-left10px

        HTML

        ltdivgt ltpgtHelloltpgtltdivgtltpgtltpgt

        offset

        Get the current coordinates of the f irst element in the set of matched elements relat ive to thedocument

        Added in version 12

        offset()Object

        The of fset() method allows us to retrieve the current posit ion of an element relative to thedocument Contrast this with posit ion() which retrieves the current posit ion relative to the offsetparent When posit ioning a new element on top of an exist ing one for global manipulat ion (inpart icular for implement ing drag-and-drop) of fset() is the more useful

        of fset() returns an object containing the propert ies top and lef t

        Note jQuery does not support getting the offset coordinates of hidden elements oraccounting for borders margins or padding set on the body element

        Example 1 Access the of fset of the second paragraph

        Javascript

        var p = $(plast)var offset = poffset()phtml( left + offsetleft + top + offsettop )

        CSS

        p margin-left10px

        HTML

        ltpgtHelloltpgtltpgt2nd Paragraphltpgt

        Example 2 Click to see the of fset

        Javascript

        $( documentbody)cl ick(function (e) var offset = $(this)offset() estopPropagation() $(result)text(thistagName + coords ( + offsetleft + + offsettop + )))

        CSS

        p margin-left10px colorblue width200px cursorpointer span colorred cursorpointer divabs width50px height50px positionabsolute left220px top35px background-colorgreen cursorpointer

        HTML

        ltdiv id=resultgtClick an elementltdivgtltpgt This is the best way to ltspangtfindltspangt an offsetltpgt

        ltdiv class=absgtltdivgt

        offset

        Set the current coordinates of every element in the set of matched elements relat ive to thedocument

        Added in version 14

        offset(funct ion(index coords))jQuery

        funct ion(indexcoords)Funct ion

        A funct ion to return the coordinates to set Receives the index of theelement in the collect ion as the f irst argument and the currentcoordinates as the second argument The funct ion should return anobject with the new top and lef t propert ies

        The of fset() set ter method allows us to reposit ion an element The element s posit ion isspecif ied relative to the document If the element s posit ion style property is current ly stat ic it

        will be set to relat ive to allow for this reposit ioning

        Example 1 Set the of fset of the second paragraph

        Javascript

        $(plast)offset( top 10 left 30 )

        CSS

        p margin-left10px

        HTML

        ltpgtHelloltpgtltpgt2nd Paragraphltpgt

        css

        Get the value of a style property for the f irst element in the set of matched elements

        Added in version 10

        css(propertyName)String

        propertyNameString A CSS property

        The css() method is a convenient way to get a style property f rom the f irst matched elementespecially in light of the dif ferent ways browsers access most of those propert ies (thegetComputedStyle() method in standards-based browsers versus the currentStyle andrunt imeStyle propert ies in Internet Explorer) and the dif ferent terms browsers use for certainpropert ies For example Internet Explorers DOM implementat ion refers to the f loat property asstyleFloat while W3C standards-compliant browsers refer to it as cssFloat The css() methodaccounts for such dif ferences producing the same result no matter which term we use Forexample an element that is f loated lef t will return the string lef t for each of the following threelines

        1 $(divlef t )css(f loat )

        2 $(divlef t )css(cssFloat )

        3 $(divlef t )css(styleFloat )

        Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color)and css(backgroundColor) Dif ferent browsers may return CSS color values that are logicallybut not textually equal eg FFF f f f f f f and rgb(255255255)

        but not textually equal eg FFF f f f f f f and rgb(255255255)

        Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

        Example 1 To access the background color of a clicked div

        Javascript

        $(div)cl ick(function () var color = $(this)css(background-color) $(result)html(That div is ltspan style=color + color + gt + color + ltspangt))

        CSS

        div width60px height60px margin5px floatleft

        HTML

        ltspan id=resultgtampnbspltspangtltdiv style=background-colorbluegtltdivgtltdiv style=background-colorrgb(159930)gtltdivgt

        ltdiv style=background-color123456gtltdivgtltdiv style=background-colorf11gtltdivgt

        css

        Set one or more CSS propert ies for the set of matched elements

        Added in version 10

        css(map)jQuery

        mapMap A map of property-value pairs to set

        As with the prop() method the css() method makes sett ing propert ies of elements quick andeasy This method can take either a property name and value as separate parameters or asingle map of key-value pairs (JavaScript object notat ion)

        Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color

        f fe border-lef t 5px solid ccc) and css(backgroundColor f fe borderLeft 5px solidccc) Not ice that with the DOM notat ion quotat ion marks around the property names areopt ional but with CSS notat ion theyre required due to the hyphen in the name

        When using css() as a setter jQuery modif ies the element s style property For example$(mydiv)css(color green) is equivalent to documentgetElementById(mydiv)stylecolor =green Sett ing the value of a style property to an empty string acirceurordquo eg $(mydiv)css(color )acirceurordquo removes that property f rom an element if it has already been direct ly applied whether in theHTML style at t ribute through jQuerys css() method or through direct DOM manipulat ion ofthe style property It does not however remove a style that has been applied with a CSS rule ina stylesheet or ltstylegt element

        As of jQuery 16 css() accepts relat ive values similar to animate() Relat ive values are a stringstart ing with += or -= to increment or decrement the current value For example if an element spadding-lef t was 10px css( padding-lef t +=15 ) would result in a total padding-lef t of 25px

        As of jQuery 14 css() allows us to pass a funct ion as the property value

        $(divexample)css(width function(index) return index 50)

        This example sets the widths of the matched elements to incrementally larger values

        Note If nothing is returned in the setter funct ion (ie funct ion(index style)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met

        Example 1 To change the color of any paragraph to red on mouseover event

        Javascript

        $(p)mouseover(function () $(this)css(colorred) )

        CSS

        p colorblue width200px font-size14px

        HTML

        ltpgtJust roll the mouse over meltpgt

        ltpgtOr me to see a color changeltpgt

        Example 2 Increase the width of box by 200 pixels

        Javascript

        $(box)one( cl ick function () $( this )css( width+=200 ) )

        CSS

        box background black color snow width100px padding10px

        HTML

        ltdiv id=boxgtClick me to growltdivgt

        Example 3 To highlight a clicked word in the paragraph

        Javascript

        var words = $(pfirst)text()split( ) var text = wordsjoin(ltspangt ltspangt) $(pfirst)html(ltspangt + text + ltspangt) $(span)cl ick(function () $(this)css(background-coloryellow) )

        CSS

        p colorblue font-weightbold cursorpointer

        HTML

        ltpgt Once upon a time there was a man who l ived in a pizza parlor This man just loved pizza and ate it al l the time He went on to be the happiest man in the world The endltpgt

        Example 4 To set the color of all paragraphs to red and background to blue

        Javascript

        $(p)hover(function () $(this)css(background-color yellow font-weight bolder) function () var cssObj = background-color ddd font-weight color rgb(040244) $(this)css(cssObj) )

        CSS

        p colorgreen

        HTML

        ltpgtMove the mouse over a paragraphltpgt ltpgtLike this one or the one aboveltpgt

        Example 5 Increase the size of a div when you click it

        Javascript

        $(div)cl ick(function() $(this)css( width function(index value) return parseFloat(value) 12 height function(index value) return parseFloat(value) 12

        ) )

        CSS

        div width 20px height 15px background-color f33

        HTML

        ltdivgtclickltdivgt ltdivgtclickltdivgt

        toggleClass see Attributes

        removeClass see Attributes

        hasClass see Attributes

        addClass see Attributes

        Manipulation

        removeProp see Attributes

        prop see Attributes

        prop see Attributes

        outerWidth see CSS

        outerHeight see CSS

        innerWidth see CSS

        innerHeight see CSS

        width see CSS

        width see CSS

        height see CSS

        height see CSS

        scrollLeft see CSS

        scrollLeft see CSS

        scrollTop see CSS

        scrollTop see CSS

        position see CSS

        offset see CSS

        offset see CSS

        css see CSS

        css see CSS

        unwrap

        Remove the parents of the set of matched elements f rom the DOM leaving the matchedelements in their place

        Added in version 14

        unwrap()jQuery

        The unwrap() method removes the element s parent This is ef fect ively the inverse of thewrap() method The matched elements (and their siblings if any) replace their parents withinthe DOM structure

        Example 1 Wrapunwrap a div around each of the paragraphs

        Javascript

        $(button)toggle(function() $(p)wrap(ltdivgtltdivgt) function() $(p)unwrap())

        CSS

        div border 2px solid blue p backgroundyellow margin4px

        HTML

        ltbuttongtwrapunwrapltbuttongtltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

        detach

        Remove the set of matched elements f rom the DOM

        Added in version 14

        detach(selector)jQuery

        selectorSelector (opt ional) A selector expression that f ilters the set of matchedelements to be removed

        The detach() method is the same as remove() except that detach() keeps all jQuery dataassociated with the removed elements This method is useful when removed elements are tobe reinserted into the DOM at a later t ime

        Example 1 Detach all paragraphs from the DOM

        Javascript

        $(p)cl ick(function() $(this)toggleClass(off) ) var p $(button)cl ick(function() i f ( p ) pappendTo(body) p = null else p = $(p)detach() )

        CSS

        p backgroundyellow margin6px 0 poff background black

        HTML

        ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtAttachdetach paragraphsltbuttongt

        clone

        Create a deep copy of the set of matched elements

        Added in version 15

        clone(withDataAndEvents deepWithDataAndEvents)jQuery

        withDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data should be copied along with the

        elements The default value is false In jQuery 150the default value was incorrectly true it was changedback to false in 151 and up

        deepWithDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data for all children of the clonedelement should be copied By default its valuematches the f irst argument s value (which defaultsto false)

        The clone() method performs a deep copy of the set of matched elements meaning that itcopies the matched elements as well as all of their descendant elements and text nodes Whenused in conjunct ion with one of the insert ion methods clone() is a convenient way to duplicateelements on a page Consider the following HTML

        ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        As shown in the discussion for append() normally when an element is inserted somewhere inthe DOM it is moved from its old locat ion So given the code

        $(hello)appendTo(goodbye)

        The result ing DOM structure would be

        ltdiv class=containergt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

        To prevent this and instead create a copy of the element you could write the following

        $(hello)clone()appendTo(goodbye)

        This would produce

        ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt

        Note that when using the clone() method you can modify the cloned elements ortheir contents before (re-)inserting them into the document

        Normally any event handlers bound to the original element are not copied to the clone Theopt ional withDataAndEvents parameter allows us to change this behavior and to instead makecopies of all of the event handlers as well bound to the new copy of the element As of jQuery14 all element data (at tached by the data() method) is also copied to the new copy

        However objects and arrays within element data are not copied and will cont inue to be sharedbetween the cloned element and the original element To deep copy all data copy each onemanually

        var $elem = $(elem)data( arr [ 1 ] ) Original element with attached data $clone = $elemclone( true ) data( arr $extend( [] $elemdata(arr) ) ) Deep copy to prevent data sharing

        As of jQuery 15 withDataAndEvents can be opt ionally enhanced withdeepWithDataAndEvents to copy the events and data for all children of the cloned element

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

        Javascript

        $(b)clone()prependTo(p)

        HTML

        ltbgtHelloltbgtltpgt how are youltpgt

        Example 2 When using clone() to clone a collect ion of elements that are not at tached to theDOM their order when inserted into the DOM is not guaranteed However it may be possible topreserve sort order with a workaround as demonstrated

        CSS

        orig copy copy-correct float left width 20

        Javascript

        sort order is not guaranteed here and may vary with browser $(copy)append($(orig elem) clone() children(a) prepend(foo - ) parent() clone()) correct way to approach where order is maintained$(copy-correct) append($(orig elem) clone() children(a) prepend(bar - ) end())

        HTML

        ltdiv id=origgt ltdiv class=elemgtltagt1ltagtltdivgt ltdiv class=elemgtltagt2ltagtltdivgt ltdiv class=elemgtltagt3ltagtltdivgt ltdiv class=elemgtltagt4ltagtltdivgt ltdiv class=elemgtltagt5ltagtltdivgtltdivgtltdiv id=copygtltdivgtltdiv id=copy-correctgtltdivgt

        remove

        Remove the set of matched elements f rom the DOM

        Added in version 10

        remove(selector)jQuery

        selectorString (opt ional) A selector expression that f ilters the set of matchedelements to be removed

        Similar to empty() the remove() method takes elements out of the DOM Use remove() when

        you want to remove the element itself as well as everything inside it In addit ion to theelements themselves all bound events and jQuery data associated with the elements areremoved To remove the elements without removing data and events use detach() instead

        Consider the following HTML

        ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        We can target any element for removal

        $(hello)remove()

        This will result in a DOM structure with the ltdivgt element deleted

        ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo Other jQuery constructs such as data or event handlers are erased as well

        We can also include a selector as an opt ional parameter For example we could rewrite theprevious DOM removal code as follows

        $(div)remove(hello)

        This would result in the same DOM structure

        ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        Example 1 Removes all paragraphs from the DOM

        Javascript

        $(button)cl ick(function () $(p)remove() )

        CSS

        p backgroundyellow margin6px 0

        HTML

        ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtCall remove() on paragraphsltbuttongt

        Example 2 Removes all paragraphs that contain Hello f rom the DOM Analogous to doing$(p)f ilter(contains(Hello))remove()

        Javascript

        $(button)cl ick(function () $(p)remove(contains(Hello)) )

        CSS

        p backgroundyellow margin6px 0

        HTML

        ltp class=hellogtHelloltpgt how are ltpgtyoultpgt

        ltbuttongtCall remove(contains(Hello)) on paragraphsltbuttongt

        empty

        Remove all child nodes of the set of matched elements f rom the DOM

        Added in version 10

        empty()jQuery

        This method removes not only child (and other descendant) elements but also any text withinthe set of matched elements This is because according to the DOM specif icat ion any stringof text within an element is considered a child node of that element Consider the followingHTML

        ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        We can target any element for removal

        $(hello)empty()

        This will result in a DOM structure with the Hello text deleted

        ltdiv class=containergt ltdiv class=hellogtltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt

        If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo

        To avoid memory leaks jQuery removes other constructs such as data and event handlersfrom the child elements before removing the elements themselves

        Example 1 Removes all child nodes (including text nodes) f rom all paragraphs

        Javascript

        $(button)cl ick(function () $(p)empty() )

        CSS

        p backgroundyellow

        HTML

        ltpgt Hello ltspangtPersonltspangt lta href=javascriptgtand personltagtltpgt

        ltbuttongtCall empty() on above paragraphltbuttongt

        replaceAll

        Replace each target element with the set of matched elements

        Added in version 12

        replaceAll(target)jQuery

        targetSelector A selector expression indicat ing which element(s) to replace

        The replaceAll() method is corollary to replaceWith() but with the source and target reversedConsider this DOM structure

        ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

        We can create an element then replace other elements with it

        $(lth2gtNew headinglth2gt)replaceAll( inner)

        This causes all of them to be replaced

        ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

        Or we could select an element to use as the replacement

        $(first)replaceAll( third)

        This results in the DOM structure

        ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

        From this example we can see that the selected element replaces the target by being movedfrom its old locat ion not by being cloned

        Example 1 Replace all the paragraphs with bold words

        Javascript

        $(ltbgtParagraph ltbgt)replaceAll(p) check replaceWith() examples

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        replaceWith

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

        Added in version 14

        replaceWith(funct ion)jQuery

        funct ionFunct ion A funct ion that returns content with which to replace the set ofmatched elements

        The replaceWith() method removes content f rom the DOM and inserts new content in its placewith a single call Consider this DOM structure

        ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

        The second inner ltdivgt could be replaced with the specif ied HTML

        $(divsecond)replaceWith(lth2gtNew headinglth2gt)

        This results in the structure

        ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt lth2gtNew headinglth2gt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt

        All inner ltdivgt elements could be targeted at once

        $(divinner)replaceWith(lth2gtNew headinglth2gt)

        This causes all of them to be replaced

        ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt

        An element could also be selected as the replacement

        $(divthird)replaceWith($(first))

        This results in the DOM structure

        ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt

        This example demonstrates that the selected element replaces the target by being moved fromits old locat ion not by being cloned

        The replaceWith() method like most jQuery methods returns the jQuery object so that othermethods can be chained onto it However it must be noted that the original jQuery object isreturned This object refers to the element that has been removed from the DOM not the newelement that has replaced it

        As of jQuery 14 replaceWith() can also work on disconnected DOM nodes For example withthe following code replaceWith() returns a jQuery set containing only a paragraph

        $(ltdivgt)replaceWith(ltpgtltpgt)

        The replaceWith() method can also take a funct ion as its argument

        $(divcontainer)replaceWith(function() return $(this)contents())

        This results in ltdiv class=containergt being replaced by its three child ltdivgts The return valueof the funct ion may be an HTML string DOM element or jQuery object

        Example 1 On click replace the button with a div containing the same word

        Javascript

        $(button)cl ick(function () $(this)replaceWith( ltdivgt + $(this)text() + ltdivgt ))

        CSS

        button displayblock margin3px colorred width200px div colorred border2px solid blue width200px margin3px text-aligncenter

        HTML

        ltbuttongtFirstltbuttongtltbuttongtSecondltbuttongtltbuttongtThirdltbuttongt

        Example 2 Replace all paragraphs with bold words

        Javascript

        $(p)replaceWith( ltbgtParagraph ltbgt )

        HTML

        ltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt

        Example 3 On click replace each paragraph with a div that is already in the DOM and selectedwith the $() funct ion Not ice it doesnt clone the object but rather moves it to replace theparagraph

        Javascript

        $(p)cl ick(function () $(this)replaceWith( $(div) ))

        CSS

        div border2px solid blue colorred margin3px p border2px solid red colorblue margin3px cursorpointer

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        ltdivgtReplacedltdivgt

        Example 4 On button click replace the containing div with its child divs and append the classname of the selected element to the paragraph

        Javascript

        $(button)bind(click function() var $container = $(divcontainer)replaceWith(function() return $(this)contents() )

        $(p)append( $containerattr(class) ))

        CSS

        container background-color 991 inner color 911

        HTML

        ltpgt ltbuttongtReplaceltbuttongtltpgtltdiv class=containergt ltdiv class=innergtScoobyltdivgt ltdiv class=innergtDoobyltdivgt ltdiv class=innergtDooltdivgtltdivgt

        wrapInner

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

        Added in version 14

        wrapInner(funct ion(index))jQuery

        funct ion(index)Funct ion A callback funct ion which generates a structure to wraparound the content of the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

        The wrapInner() funct ion can take any string or object that could be passed to the $() factoryfunct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element The structure will be wrapped around the content ofeach of the elements in the set of matched elements

        Consider the following HTML

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        Using wrapInner() we can insert an HTML structure around the content of each inner ltdivgtelements like so

        $(inner)wrapInner(ltdiv class=new gt)

        The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around the content of each matched element

        ltdiv class=containergt ltdiv class=innergt ltdiv class=newgtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=newgtGoodbyeltdivgt ltdivgtltdivgt

        The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the content of the correspondingelement For example

        $(inner)wrapInner(function() return ltdiv class= + thisnodeValue + gt)

        This will cause each ltdivgt to have a class corresponding to the text it wraps

        ltdiv class=containergt ltdiv class=innergt ltdiv class=HellogtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=GoodbyegtGoodbyeltdivgt ltdivgtltdivgt

        Note When passing a selector string to the wrapInner() funct ion the expected input is wellformed HTML with correct ly closed tags Examples of valid input include

        $(elem)wrapInner(ltdiv class=test gt)$(elem)wrapInner(ltdiv class=testgtltdivgt)$(elem)wrapInner(ltdiv class=testgtltdivgt)

        Example 1 Selects all paragraphs and wraps a bold tag around each of its contents

        Javascript

        $(p)wrapInner(ltbgtltbgt)

        CSS

        p backgroundbbf

        HTML

        ltpgtHelloltpgt

        ltpgtcruelltpgt ltpgtWorldltpgt

        Example 2 Wraps a newly created tree of objects around the inside of the body

        Javascript

        $(body)wrapInner(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

        CSS

        div border2px green solid margin2px padding2px p backgroundyellow margin2px padding2px

        HTML

        Plain old text or is it

        Example 3 Selects all paragraphs and wraps a bold tag around each of its contents

        Javascript

        $(p)wrapInner(documentcreateElement(b))

        CSS

        p background9f9

        HTML

        ltpgtHelloltpgt

        ltpgtcruelltpgt ltpgtWorldltpgt

        Example 4 Selects all paragraphs and wraps a jQuery object around each of its contents

        Javascript

        $(p)wrapInner($(ltspan class=redgtltspangt))

        CSS

        p background9f9 red colorred

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        wrapAll

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

        Added in version 12

        wrapAll(wrappingElement)jQuery

        wrappingElementStringSelector ElementjQuery

        An HTML snippet selector expression jQuery object or DOMelement specifying the structure to wrap around the matchedelements

        The wrapAll() funct ion can take any string or object that could be passed to the $() funct ion tospecify a DOM structure This structure may be nested several levels deep but should containonly one inmost element The structure will be wrapped around all of the elements in the set ofmatched elements as a single group

        Consider the following HTML

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        Using wrapAll() we can insert an HTML structure around the inner ltdivgt elements like so

        $(inner)wrapAll(ltdiv class=new gt)

        The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around all matched elements

        ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

        Example 1 Wrap a new div around all of the paragraphs

        Javascript

        $(p)wrapAll(ltdivgtltdivgt)

        CSS

        div border 2px solid blue p backgroundyellow margin4px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

        Javascript

        $(span)wrapAll(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

        CSS

        div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

        HTML

        ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

        Example 3 Wrap a new div around all of the paragraphs

        Javascript

        $(p)wrapAll(documentcreateElement(div))

        CSS

        div border 2px solid blue p backgroundyellow margin4px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

        Javascript

        $(p)wrapAll($(doublediv))

        CSS

        div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

        wrap

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

        Added in version 14

        wrap(funct ion(index))jQuery

        funct ion(index)Funct ion A callback funct ion returning the HTML content or jQueryobject to wrap around the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset

        The wrap() funct ion can take any string or object that could be passed to the $() factory

        funct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element A copy of this structure will be wrapped around eachof the elements in the set of matched elements This method returns the original set ofelements for chaining purposes

        Consider the following HTML

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        Using wrap() we can insert an HTML structure around the inner ltdivgt elements like so

        $(inner)wrap(ltdiv class=new gt)

        The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around each matched element

        ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=newgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

        The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the corresponding element Forexample

        $(inner)wrap(function() return ltdiv class= + $(this)text() + gt)

        This will cause each ltdivgt to have a class corresponding to the text it wraps

        ltdiv class=containergt ltdiv class=Hellogt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=Goodbyegt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt

        Example 1 Wrap a new div around all of the paragraphs

        Javascript

        $(p)wrap(ltdivgtltdivgt)

        CSS

        div border 2px solid blue p backgroundyellow margin4px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html

        Javascript

        $(span)wrap(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)

        CSS

        div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred

        HTML

        ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt

        Example 3 Wrap a new div around all of the paragraphs

        Javascript

        $(p)wrap(documentcreateElement(div))

        CSS

        div border 2px solid blue p backgroundyellow margin4px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt

        Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target

        Javascript

        $(p)wrap($(doublediv))

        CSS

        div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px

        HTML

        ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt

        insertBefore

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

        Added in version 10

        insertBefore(target)jQuery

        targetSelectorElementjQuery

        A selector element HTML string or jQuery object the matched set ofelements will be inserted before the element(s) specif ied by thisparameter

        The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

        Consider the following HTML

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        We can create content and insert it before several elements at once

        $(ltpgtTestltpgt)insertBefore(inner)

        Each inner ltdivgt element gets this new content

        ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Example 1 Inserts all paragraphs before an element with id of foo Same as$( foo)before(p)

        Javascript

        $(p)insertBefore(foo) check before() examples

        CSS

        foo backgroundyellow

        HTML

        ltdiv id=foogtFOOltdivgtltpgtI would l ike to say ltpgt

        before

        Insert content specif ied by the parameter before each element in the set of matchedelements

        Added in version 14

        before(funct ion)jQuery

        funct ionFunct ion A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert before each element in the set of matched elementsReceives the index posit ion of the element in the set as anargument Within the funct ion this refers to the current element inthe set

        The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container

        Consider the following HTML

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        You can create content and insert it before several elements at once

        $(inner)before(ltpgtTestltpgt)

        Each inner ltdivgt element gets this new content

        ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt

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

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        In jQuery 14 before() and af ter() will also work on disconnected DOM nodes

        $(ltdivgt)before(ltpgtltpgt)

        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 prepend() and af ter() before() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

        For example the following will insert two new ltdivgts and an exist ing ltdivgt before the f irstparagraph

        var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

        $(p)first()before($newdiv1 [newdiv2 existingdiv1])

        Since before() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so$(p)f irst()before($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

        Example 1 Inserts some HTML before all paragraphs

        Javascript

        $(p)before(ltbgtHelloltbgt)

        CSS

        p backgroundyellow

        HTML

        ltpgt is what I saidltpgt

        Example 2 Inserts a DOM element before all paragraphs

        Javascript

        $(p)before( documentcreateTextNode(Hello) )

        CSS

        p backgroundyellow

        HTML

        ltpgt is what I saidltpgt

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

        Javascript

        $(p)before( $(b) )

        CSS

        p backgroundyellow

        HTML

        ltpgt is what I saidltpgtltbgtHelloltbgt

        insertAfter

        Insert every element in the set of matched elements af ter the target

        Added in version 10

        insertAfter(target)jQuery

        targetSelectorElementjQuery

        A selector element HTML string or jQuery object the matched set ofelements will be inserted af ter the element(s) specif ied by thisparameter

        The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

        Consider the following HTML

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        We can create content and insert it af ter several elements at once

        $(ltpgtTestltpgt)insertAfter( inner)

        Each inner ltdivgt element gets this new content

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

        We can also select an element on the page and insert it af ter another

        $(h2)insertAfter($(container))

        If an element selected this way is inserted elsewhere it will be moved af ter the target (notcloned)

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Example 1 Inserts all paragraphs af ter an element with id of foo Same as $( foo)af ter(p)

        Javascript

        $(p)insertAfter(foo) check after() examples

        CSS

        foo backgroundyellow

        HTML

        ltpgt is what I said ltpgtltdiv id=foogtFOOltdivgt

        after

        Insert content specif ied by the parameter af ter each element in the set of matched elements

        Added in version 14

        after(funct ion(index))jQuery

        funct ion(index)Funct ion A funct ion that returns an HTML string DOM element(s) orjQuery object to insert af ter each element in the set ofmatched elements Receives the index posit ion of theelement in the set as an argument Within the funct ion thisrefers to the current element in the set

        The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container

        Using the following HTML

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        Content can be created and then inserted af ter several elements at once

        $(inner)after(ltpgtTestltpgt)

        Each inner ltdivgt element gets this new content

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt

        An element in the DOM can also be selected and inserted af ter another element

        $(container)after($(h2))

        If an element selected this way is inserted elsewhere it will be moved rather than cloned

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Inserting Disconnected DOM nodes

        As of jQuery 14 before() and af ter() will also work on disconnected DOM nodes For examplegiven the following code

        $(ltdivgt)after(ltpgtltpgt)

        The result is a jQuery set containing a div and a paragraph in that order That set can befurther manipulated even before it is inserted in the document

        $(ltdivgt)after(ltpgtltpgt)addClass(foo) fi lter(p)attr( id bar)html(hello)end()appendTo(body)

        This results in the following elements inserted just before the closing ltbodygt tag

        ltdiv class=foogtltdivgtltp class=foo id=bargthelloltpgt

        Passing a Function

        As of jQuery 14 af ter() supports passing a funct ion that returns the elements to insert

        $(p)after(function() return ltdivgt + thisclassName + ltdivgt)

        This example inserts a ltdivgt af ter each paragraph with each new ltdivgt containing the class

        name(s) of its preceding paragraph

        Additional Arguments

        Similar to other content-adding methods such as prepend() and before() af ter() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements

        For example the following will insert two new ltdivgts and an exist ing ltdivgt af ter the f irstparagraph

        var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

        $(p)first()after($newdiv1 [newdiv2 existingdiv1])

        Since af ter() can accept any number of addit ional arguments the same result can be achievedby passing in the three ltdivgts as three separate arguments like so $(p)f irst()af ter($newdiv1newdiv2 exist ingdiv1) The type and number of arguments will largely depend on the elementsare collected in the code

        Example 1 Inserts some HTML after all paragraphs

        Javascript

        $(p)after(ltbgtHelloltbgt)

        CSS

        p backgroundyellow

        HTML

        ltpgtI would l ike to say ltpgt

        Example 2 Inserts a DOM element af ter all paragraphs

        Javascript

        $(p)after( documentcreateTextNode(Hello) )

        CSS

        p backgroundyellow

        HTML

        ltpgtI would l ike to say ltpgt

        Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) af ter all paragraphs

        Javascript

        $(p)after( $(b) )

        CSS

        p backgroundyellow

        HTML

        ltbgtHelloltbgtltpgtI would l ike to say ltpgt

        prependTo

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

        Added in version 10

        prependTo(target)jQuery

        targetSelectorElementjQuery

        A selector element HTML string or jQuery object the matched set ofelements will be inserted at the beginning of the element(s) specif iedby this parameter

        The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

        Consider the following HTML

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        We can create content and insert it into several elements at once

        $(ltpgtTestltpgt)prependTo(inner)

        Each inner ltdivgt element gets this new content

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

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

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Example 1 Prepends all spans to the element with the ID foo

        CSS

        div backgroundyellow

        Javascript

        $(span)prependTo(foo) check prepend() examples

        HTML

        ltdiv id=foogtFOOltdivgt

        ltspangtI have something to say ltspangt

        prepend

        Insert content specif ied by the parameter to the beginning of each element in the set ofmatched elements

        Added in version 14

        prepend(funct ion(index html))jQuery

        funct ion(indexhtml)Funct ion

        A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the beginning of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

        The prepend() method inserts the specif ied content as the f irst child of each element in thejQuery collect ion (To insert it as the last child use append())

        The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

        Consider the following HTML

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        You can create content and insert it into several elements at once

        $(inner)prepend(ltpgtTestltpgt)

        Each ltdiv class=innergt element gets this new content

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt

        You can also select an element on the page and insert it into another

        $(container)prepend($(h2))

        If a single element selected this way is inserted elsewhere it will be moved into the target (notcloned)

        ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        Important If there is more than one target element however cloned copies of the insertedelement will be created for each target af ter the f irst

        Additional Arguments

        Similar to other content-adding methods such as append() and before() prepend() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

        For example the following will insert two new ltdivgts and an exist ing ltdivgt as the f irst threechild nodes of the body

        var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

        $(body)prepend($newdiv1 [newdiv2 existingdiv1])

        Since prepend() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

        $(body)prepend($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

        Example 1 Prepends some HTML to all paragraphs

        Javascript

        $(p)prepend(ltbgtHello ltbgt)

        CSS

        p backgroundyellow

        HTML

        ltpgtthere friendltpgt

        ltpgtamigoltpgt

        Example 2 Prepends a DOM Element to all paragraphs

        Javascript

        $(p)prepend(documentcreateTextNode(Hello ))

        CSS

        p backgroundyellow

        HTML

        ltpgtis what Id sayltpgtltpgtis what I saidltpgt

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

        Javascript

        $(p)prepend( $(b) )

        CSS

        p backgroundyellow

        HTML

        ltpgt is what was saidltpgtltbgtHelloltbgt

        appendTo

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

        Added in version 10

        appendTo(target)jQuery

        targetSelectorElementjQuery

        A selector element HTML string or jQuery object the matched set ofelements will be inserted at the end of the element(s) specif ied by thisparameter

        The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

        Consider the following HTML

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        We can create content and insert it into several elements at once

        $(ltpgtTestltpgt)appendTo(inner)

        Each inner ltdivgt element gets this new content

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Example 1 Appends all spans to the element with the ID foo

        Javascript

        $(span)appendTo(foo) check append() examples

        CSS

        foo backgroundyellow

        HTML

        ltspangtI have nothing more to say ltspangt

        ltdiv id=foogtFOO ltdivgt

        append

        Insert content specif ied by the parameter to the end of each element in the set of matchedelements

        Added in version 14

        append(funct ion(index html))jQuery

        funct ion(indexhtml)Funct ion

        A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the end of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set

        The append() method inserts the specif ied content as the last child of each element in thejQuery collect ion (To insert it as the first child use prepend())

        The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container

        Consider the following HTML

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt

        You can create content and insert it into several elements at once

        $(inner)append(ltpgtTestltpgt)

        Each inner ltdivgt element gets this new content

        lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt

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

        ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt

        If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst

        Additional Arguments

        Similar to other content-adding methods such as prepend() and before() append() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements

        For example the following will insert two new ltdivgts and an exist ing ltdivgt as the last threechild nodes of the body

        var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)

        $(body)append($newdiv1 [newdiv2 existingdiv1])

        Since append() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so

        $(body)append($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code

        Example 1 Appends some HTML to all paragraphs

        Javascript

        $(p)append(ltstronggtHelloltstronggt)

        CSS

        p backgroundyellow

        HTML

        ltpgtI would l ike to say ltpgt

        Example 2 Appends an Element to all paragraphs

        Javascript

        $(p)append(documentcreateTextNode(Hello))

        CSS

        p backgroundyellow

        HTML

        ltpgtI would l ike to say ltpgt

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

        Javascript

        $(p)append( $(strong) )

        CSS

        p backgroundyellow

        HTML

        ltstronggtHello worldltstronggtltpgtI would l ike to say ltpgt

        val see Attributes

        val see Attributes

        text

        Get the combined text contents of each element in the set of matched elements includingtheir descendants

        Added in version 10

        text()String

        Unlike the html() method text() can be used in both XML and HTML documents The result ofthe text() method is a string containing the combined text of all matched elements (Due tovariat ions in the HTML parsers in dif ferent browsers the text returned may vary in newlines andother white space) Consider the following HTML

        ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgt ltdivgt

        The code $(divdemo-container)text() would produce the following result

        Demonstrat ion Box list item 1 list item 2

        The text() method cannot be used on form inputs or scripts To set or get the text value ofinput or textarea elements use the val() method To get the value of a script element use thehtml() method

        As of jQuery 14 the text() method returns the value of text and CDATA nodes as well aselement nodes

        Example 1 Find the text in the f irst paragraph (stripping out the html) then set the html of thelast paragraph to show it is just text (the red bold is gone)

        Javascript

        var str = $(pfirst)text() $(plast)html(str)

        CSS

        p colorblue margin8px b colorred

        HTML

        ltpgtltbgtTestltbgt Paragraphltpgt

        ltpgtltpgt

        text

        Set the content of each element in the set of matched elements to the specif ied text

        Added in version 14

        text(funct ion(index text))jQuery

        funct ion(indextext)Funct ion

        A funct ion returning the text content to set Receives the indexposit ion of the element in the set and the old text value as arguments

        Unlike the html() method text() 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 willrender correct ly in HTML To do so it calls the DOM method createTextNode() which replacesspecial characters with their HTML ent ity equivalents (such as amplt for lt) Consider the followingHTML

        ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgtltdivgt

        The code $(divdemo-container)text(ltpgtThis is a test ltpgt) will produce the following DOMoutput

        ltdiv class=demo-containergtampltpampgtThis is a testampltpampgtltdivgt

        It will appear on a rendered page as though the tags were exposed like this

        ltpgtThis is a testltpgt

        The text() method cannot be used on input elements For input f ield text use the val() method

        As of jQuery 14 the text() method allows us to set the text content by passing in a funct ion

        $(ul l i )text(function(index) return item number + (index + 1))

        Given an unordered list with three ltligt elements this example will produce the following DOMoutput

        ltulgt ltligtitem number 1ltligt ltligtitem number 2ltligt ltligtitem number 3ltligtltulgt

        Example 1 Add text to the paragraph (not ice the bold tag is escaped)

        Javascript

        $(p)text(ltbgtSomeltbgt new text)

        CSS

        p colorblue margin8px

        HTML

        ltpgtTest Paragraphltpgt

        html see Attributes

        html see Attributes

        toggleClass see Attributes

        removeClass see Attributes

        hasClass see Attributes

        removeAttr see Attributes

        attr see Attributes

        attr see Attributes

        addClass see Attributes

        Data

        jQueryhasData

        Determine whether an element has any jQuery data associated with it

        Added in version 15

        jQueryhasData(element)Boolean

        elementElement A DOM element to be checked for data

        The jQueryhasData() method provides a way to determine if an element current ly has anyvalues that were set using jQuerydata() If no data is associated with an element (there is nodata object at all or the data object is empty) the method returns false otherwise it returnstrue

        The primary advantage of jQueryhasData(element) is that it does not create and associate adata object with the element if none current ly exists In contrast jQuerydata(element) alwaysreturns a data object to the caller creat ing one if no data object previously existed

        Example 1 Set data on an element and see the results of hasData

        Javascript

        $(function() var $p = jQuery(p) p = $p[0] $pappend(jQueryhasData(p)+ ) false jQuerydata(p testing 123) $pappend(jQueryhasData(p)+ ) true jQueryremoveData(p testing) $pappend(jQueryhasData(p)+ ) false )

        HTML

        ltpgtResults ltpgt

        jQueryremoveData

        Remove a previously-stored piece of data

        Added in version 123

        jQueryremoveData(element name)jQuery

        elementElement A DOM element f rom which to remove data

        nameString (opt ional) A string naming the piece of data to remove

        Note This is a low-level method you should probably use removeData() instead

        The jQueryremoveData() method allows us to remove values that were previously set usingjQuerydata() When called with the name of a key jQueryremoveData() deletes that part icularvalue when called with no arguments all values are removed

        Example 1 Set a data store for 2 names then remove one of them

        Javascript

        var div = $(div)[0]$(spaneq(0))text( + $(div)data(test1))jQuerydata(div test1 VALUE-1)jQuerydata(div test2 VALUE-2)$(spaneq(1))text( + jQuerydata(div test1))jQueryremoveData(div test1)$(spaneq(2))text( + jQuerydata(div test1))$(spaneq(3))text( + jQuerydata(div test2))

        CSS

        div margin2px colorblue span colorred

        HTML

        ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt ltdivgtvalue2 after removal ltspangtltspangtltdivgt

        jQuerydata

        Store arbit rary data associated with the specif ied element Returns the value that was set

        Added in version 123

        jQuerydata(element key value)Object

        elementElement The DOM element to associate with the data

        keyString A string naming the piece of data to set

        valueObject The new data value

        Note This is a low-level method a more convenient data() is also available

        The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f ree from memory leaks jQuery ensures that thedata is removed when DOM elements are removed via jQuery methods and when the userleaves the page We can set several dist inct values for a single element and retrieve them later

        jQuerydata(documentbody foo 52)jQuerydata(documentbody bar test)

        Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

        Example 1 Store then retrieve a value from the div element

        Javascript

        var div = $(div)[0] jQuerydata(div test first 16 last pizza ) $(spanfirst)text(jQuerydata(div test)first) $(spanlast)text(jQuerydata(div test)last)

        CSS

        div colorblue span colorred

        HTML

        ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

        jQuerydata

        Returns value at named data store for the element as set by jQuerydata(element namevalue) or the full data store for the element

        Added in version 14

        jQuerydata(element)Object

        elementElement The DOM element to query for the data

        Note This is a low-level method a more convenient data() is also available

        Regarding HTML5 data- at t ributes This low-level method does NOT retrieve the data-at t ributes unless the more convenient data() method has already retrieved them

        The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f rom memory leaks We can retrieve severaldist inct values for a single element one at a t ime or as a set

        alert(jQuerydata( documentbody foo ))alert(jQuerydata( documentbody ))

        The above lines alert the data values that were set on the body element If nothing was set onthat element an empty string is returned

        Calling jQuerydata(element) retrieves all of the element s associated values as a JavaScriptobject Note that jQuery itself uses this method to store data for internal use such as eventhandlers so do not assume that it contains only data that your own code has stored

        Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies

        Example 1 Get the data named blah stored at for an element

        Javascript

        $(button)cl ick(function(e) var value div = $(div)[0]

        switch ($(button)index(this)) case 0 value = jQuerydata(div blah) break case 1 jQuerydata(div blah hello) value = Stored break case 2 jQuerydata(div blah 86) value = Stored break case 3 jQueryremoveData(div blah) value = Removed break

        $(span)text( + value))

        CSS

        div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

        HTML

        ltdivgtA divltdivgtltbuttongtGet blah from the divltbuttongtltbuttongtSet blah to helloltbuttongt

        ltbuttongtSet blah to 86ltbuttongtltbuttongtRemove blah from the divltbuttongtltpgtThe blah value of this div is ltspangtltspangtltpgt

        jQuerydequeue

        Execute the next funct ion on the queue for the matched element

        Added in version 13

        jQuerydequeue(element queueName)jQuery

        elementElement A DOM element f rom which to remove and execute a queuedfunct ion

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        Note This is a low-level method you should probably use dequeue() instead

        When jQuerydequeue() is called the next funct ion on the queue is removed from the queueand then executed This funct ion should in turn (direct ly or indirect ly) cause jQuerydequeue() tobe called so that the sequence can cont inue

        Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

        Javascript

        $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $dequeue( this ) ) $(div)animate(left10px top30px 700) )

        CSS

        div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

        HTML

        ltbuttongtStartltbuttongt ltdivgtltdivgt

        jQueryqueue

        Show the queue of funct ions to be executed on the matched element

        Added in version 13

        jQueryqueue(element queueName)Array

        elementElement A DOM element to inspect for an at tached queue

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        Note This is a low-level method you should probably use queue() instead

        Example 1 Show the length of the queue

        Javascript

        $(show)cl ick(function () var n = jQueryqueue( $(div)[0] fx ) $(span)text(Queue length is + nlength) ) function runIt() $(div)show(slow) $(div)animate(left+=2002000) $(div)sl ideToggle(1000) $(div)sl ideToggle(fast) $(div)animate(left-=2001500) $(div)hide(slow) $(div)show(1200) $(div)sl ideUp(normal runIt) runIt()

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue span colorred

        HTML

        ltbutton id=showgtShow Length of Queueltbuttongt ltspangtltspangt ltdivgtltdivgt

        jQueryqueue

        Manipulate the queue of funct ions to be executed on the matched element

        Added in version 13

        jQueryqueue(element queueName callback())jQuery

        elementElement A DOM element on which to add a queued funct ion

        queueNameString A string containing the name of the queue Defaults to fx thestandard ef fects queue

        callback()Funct ion The new funct ion to add to the queue

        Note This is a low-level method you should probably use queue() instead

        Every element can have one or more queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion

        The jQueryqueue() method allows us to direct ly manipulate this queue of funct ions CallingjQueryqueue() with a callback is part icularly useful it allows us to place a new funct ion at theend of the queue

        Note that when adding a funct ion with jQueryqueue() we should ensure that jQuerydequeue()is eventually called so that the next funct ion in line executes

        Example 1 Queue a custom funct ion

        Javascript

        $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=200500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() )

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

        HTML

        Click here ltdivgtltdivgt

        Example 2 Set a queue array to delete the queue

        Javascript

        $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=2001500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() ) $(stop)cl ick(function () jQueryqueue( $(div)[0] fx [] ) $(div)stop() )

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

        HTML

        ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

        clearQueue

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

        Added in version 14

        clearQueue(queueName)jQuery

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        When the clearQueue() method is called all funct ions on the queue that have not beenexecuted are removed from the queue When used without an argument clearQueue()removes the remaining funct ions from fx the standard ef fects queue In this way it is similar tostop(true) However while the stop() method is meant to be used only with animat ionsclearQueue() can also be used to remove any funct ion that has been added to a genericjQuery queue with the queue() method

        Example 1 Empty the queue

        Javascript

        $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp())$(stop)cl ick(function () $(div)clearQueue() $(div)stop())

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

        HTML

        ltbutton id=startgtStartltbuttongtltbutton id=stopgtStopltbuttongtltdivgtltdivgt

        removeData

        Remove a previously-stored piece of data

        Added in version 123

        removeData(name)jQuery

        nameString (opt ional) A string naming the piece of data to delete

        The removeData() method allows us to remove values that were previously set using data()When called with the name of a key removeData() deletes that part icular value when calledwith no arguments all values are removed

        NOTE Start ing with jQuery 143 calling removeData() will cause the value of the propertybeing removed to revert to the value of the data at t ribute of the same name in the DOM ratherthan being set to undef ined

        Example 1 Set a data store for 2 names then remove one of them

        Javascript

        $(spaneq(0))text( + $(div)data(test1)) $(div)data(test1 VALUE-1) $(div)data(test2 VALUE-2) $(spaneq(1))text( + $(div)data(test1)) $(div)removeData(test1) $(spaneq(2))text( + $(div)data(test1)) $(spaneq(3))text( + $(div)data(test2))

        CSS

        div margin2px colorblue span colorred

        HTML

        ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt

        ltdivgtvalue2 after removal ltspangtltspangtltdivgt

        data

        Store arbit rary data associated with the matched elements

        Added in version 143

        data(obj)jQuery

        objObject An object of key-value pairs of data to update

        The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks

        We can set several dist inct 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 143 sett ing an element s data object with data(obj) extends the data previouslystored with that element jQuery itself uses the data() method to save informat ion under thenames events and handle and also reserves any data name start ing with an underscore (_)for internal use

        Prior to jQuery 143 (start ing in jQuery 14) the data() method completely replaced all datainstead of just extending the data object If you are using third-party plugins it may not beadvisable to completely replace the element s data object since plugins may have also setdata

        Due to the way browsers interact with plugins and external code the data() method cannot beused on ltobjectgt (unless it s a Flash plugin) ltappletgt or ltembedgt elements

        Example 1 Store then retrieve a value from the div element

        Javascript

        $(div)data(test first 16 last pizza )$(spanfirst)text($(div)data(test)first)$(spanlast)text($(div)data(test)last)

        CSS

        div colorblue span colorred

        HTML

        ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt

        data

        Returns value at named data store for the f irst element in the jQuery collect ion as set bydata(name value)

        Added in version 14

        data()Object

        The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks We can retrieve several dist inctvalues for a single element one at a t ime or as a set

        alert($(body)data(foo))alert($(body)data())

        The above lines alert the data values that were set on the body element If no data at all wasset on that element undef ined is returned

        alert( $(body)data(foo)) undefined$(body)data(bar foobar)alert( $(body)data(foobar)) foobar

        HTML 5 data- Attributes

        As of jQuery 143 HTML 5 data- at t ributes will be automat ically pulled in to jQuerys data object The treatment of at t ributes with embedded dashes was changed in jQuery 16 to conform tothe W3C HTML5 specif icat ion

        For example given the following HTML

        ltdiv data-role=page data-last-value=43 data-hidden=true data-options=nameJohngtltdivgt

        All of the following jQuery code will work

        $(div)data(role) === page$(div)data(lastValue) === 43$(div)data(hidden) === true$(div)data(options)name === John

        Every at tempt is made to convert the string to a JavaScript value (this includes booleansnumbers objects arrays and null) otherwise it is lef t as a string To retrieve the valuesat t ribute as a string without any at tempt to convert it use the at t r() method When the dataattribute is an object (starts with ) or array (starts with [) then jQueryparseJSON is used toparse the string it must follow valid JSON syntax including quoted property names The data-at t ributes are pulled in the f irst t ime the data property is accessed and then are no longeraccessed or mutated (all data values are then stored internally in jQuery)

        Calling data() with no parameters retrieves all of the values as a JavaScript object This objectcan be safely cached in a variable as long as a new object is not set with data(obj) Using theobject direct ly to get or set values is faster than making individual calls to data() to get or seteach value

        var mydata = $(mydiv)data()if ( mydatacount lt 9 ) mydatacount = 43 mydatastatus = embiggened

        Example 1 Get the data named blah stored at for an element

        Javascript

        $(button)cl ick(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))

        CSS

        div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred

        HTML

        ltdivgtA divltdivgt ltbuttongtGet blah from the divltbuttongt ltbuttongtSet blah to helloltbuttongt

        ltbuttongtSet blah to 86ltbuttongt ltbuttongtRemove blah from the divltbuttongt ltpgtThe blah value of this div is ltspangtltspangtltpgt

        dequeue

        Execute the next funct ion on the queue for the matched elements

        Added in version 12

        dequeue(queueName)jQuery

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        When dequeue() is called the next funct ion on the queue is removed from the queue and thenexecuted This funct ion should in turn (direct ly or indirect ly) cause dequeue() to be called sothat the sequence can cont inue

        Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing

        Javascript

        $(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $(this)dequeue() ) $(div)animate(left10px top30px 700))

        CSS

        div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred

        HTML

        ltbuttongtStartltbuttongt ltdivgtltdivgt

        queue

        Show the queue of funct ions to be executed on the matched elements

        Added in version 12

        queue(queueName)Array

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        Example 1 Show the length of the queue

        Javascript

        var div = $(div)

        function runIt() divshow(slow) divanimate(left+=2002000) divsl ideToggle(1000) divsl ideToggle(fast) divanimate(left-=2001500) divhide(slow) divshow(1200) divsl ideUp(normal runIt)

        function showIt() var n = divqueue(fx) $(span)text( nlength ) setTimeout(showIt 100)

        runIt()showIt()

        CSS

        div margin3px width40px height40px positionabsolute left0px top60px backgroundgreen displaynone divnewcolor backgroundblue p colorred

        HTML

        ltpgtThe queue length is ltspangtltspangtltpgt ltdivgtltdivgt

        queue

        Manipulate the queue of funct ions to be executed on the matched elements

        Added in version 12

        queue(queueName callback( next ))jQuery

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        callback( next)Funct ion

        The new funct ion to add to the queue with a funct ion to call thatwill dequeue the next item

        Every element can have one to many queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion The typical exampleof this is calling mult iple animat ion methods on an element For example

        $(foo)sl ideUp()fadeIn()

        When this statement is executed the element begins its sliding animat ion immediately but thefading transit ion is placed on the fx queue to be called only once the sliding transit ion iscomplete

        The queue() method allows us to direct ly manipulate this queue of funct ions Calling queue()with a callback is part icularly useful it allows us to place a new funct ion at the end of thequeue

        This feature is similar to providing a callback funct ion with an animat ion method but does notrequire the callback to be given at the t ime the animat ion is performed

        $(foo)sl ideUp()$(foo)queue(function() alert(Animation complete) $(this)dequeue())

        This is equivalent to

        $(foo)sl ideUp(function() alert(Animation complete))

        Note that when adding a funct ion with queue() we should ensure that dequeue() is eventuallycalled so that the next funct ion in line executes

        In jQuery 14 the funct ion that s called is passed in another funct ion as the f irst argument thatwhen called automat ically dequeues the next item and keeps the queue moving You would useit like so

        $(test)queue(function(next) Do some stuff next())

        Example 1 Queue a custom funct ion

        Javascript

        $(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=200500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() )

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

        HTML

        Click here ltdivgtltdivgt

        Example 2 Set a queue array to delete the queue

        Javascript

        $(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() ) $(stop)cl ick(function () $(div)queue(fx []) $(div)stop() )

        CSS

        div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue

        HTML

        ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt

        Forms

        submit

        Bind an event handler to the submit JavaScript event or t rigger that event on an element

        Added in version 10

        submit()jQuery

        This method is a shortcut for bind(submit handler) in the f irst variat ion and t rigger(submit ) inthe third

        The submit event is sent to an element when the user is at tempt ing to submit a form It canonly be at tached to ltformgt elements Forms can be submit ted either by clicking an explicitltinput type=submitgt ltinput type=imagegt or ltbutton type=submitgt or by pressing

        Enter when certain form elements have focus

        Depending on the browser the Enter key may only cause a form submission if theform has exactly one text field or only when there is a submit button present Theinterface should not rely on a particular behavior for this key unless the issue isforced by observing the keypress event for presses of the Enter key

        For example consider the HTML

        ltform id=target action=destinationhtmlgt ltinput type=text value=Hello there gt ltinput type=submit value=Go gtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the form

        $(target)submit(function() alert(Handler for submit() called) return false)

        Now when the form is submit ted the message is alerted This happens prior to the actualsubmission so we can cancel the submit act ion by calling preventDefault () on the event objector by returning false f rom our handler We can trigger the event manually when another elementis clicked

        $(other)cl ick(function() $(target)submit())

        After this code executes clicks on Trigger the handler will also display the message In addit ionthe default submit act ion on the form will be f ired so the form will be submit ted

        The JavaScript submit event does not bubble in Internet Explorer However scripts that rely onevent delegat ion with the submit event will work consistent ly across browsers as of jQuery 14which has normalized the event s behavior

        Example 1 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

        Javascript

        $(form)submit(function() i f ($(inputfirst)val() == correct) $(span)text(Validated)show() return true $(span)text(Not valid)show()fadeOut(1000) return false )

        CSS

        p margin0 colorblue divp margin-left10px span colorred

        HTML

        ltpgtType correct to validateltpgt ltform action=javascriptalert(success)gt ltdivgt ltinput type=text gt

        ltinput type=submit gt ltdivgt ltformgt ltspangtltspangt

        Example 2 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry

        Javascript

        $(form)submit( function () return thissome_flag_variable )

        Example 3 To trigger the submit event on the f irst form on the page t ry

        Javascript

        $(formfirst)submit()

        select

        Bind an event handler to the select JavaScript event or t rigger that event on an element

        Added in version 10

        select()jQuery

        This method is a shortcut for bind(select handler) in the f irst two variat ions andtrigger(select ) in the third

        The select event is sent to an element when the user makes a text select ion inside it Thisevent is limited to ltinput type=textgt f ields and lttextareagt boxes

        For example consider the HTML

        ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the text input

        $(target)select(function() alert(Handler for select() called))

        Now when any port ion of the text is selected the alert is displayed Merely set t ing the locat ionof the insert ion point will not t rigger the event To trigger the event manually apply select()without an argument

        $(other)cl ick(function() $(target)select())

        After this code executes clicks on the Trigger button will also alert the message

        Handler for select() called

        In addit ion the default select act ion on the f ield will be f ired so the ent ire text f ield will beselected

        The method for retrieving the current selected text differs from one browser toanother A number of jQuery plug-ins offer cross-platform solutions

        Example 1 To do something when text in input boxes is selected

        Javascript

        $(input)select( function () $(div)text(Something was selected)show()fadeOut(1000) )

        CSS

        p colorblue div colorred

        HTML

        ltpgt

        Click and drag the mouse to select text in the inputs ltpgt ltinput type=text value=Some text gt ltinput type=text value=to test on gt

        ltdivgtltdivgt

        Example 2 To trigger the select event on all input elements t ry

        Javascript

        $(input)select()

        change

        Bind an event handler to the change JavaScript event or t rigger that event on an element

        Added in version 10

        change()jQuery

        This method is a shortcut for bind(change handler) in the f irst two variat ions andtrigger(change) in the third

        The change event is sent to an element when its value changes This event is limited to ltinputgtelements lttextareagt boxes and ltselectgt elements For select boxes checkboxes and radiobuttons the event is f ired immediately when the user makes a select ion with the mouse butfor the other element types the event is deferred unt il the element loses focus

        For example consider the HTML

        ltformgt ltinput class=target type=text value=Field 1 gt ltselect class=targetgt ltoption value=option1 selected=selectedgtOption 1ltoptiongt ltoption value=option2gtOption 2ltoptiongt ltselectgtltformgtltdiv id=othergt Trigger the handlerltdivgt

        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 opt ion is selected from the dropdown the alert is displayed It is alsodisplayed if you change the text in the f ield and then click away If the f ield loses focus withoutthe contents having changed though the event is not t riggered To trigger the event manuallyapply change() without arguments

        $(other)cl ick(function() $( target)change())

        After this code executes clicks on Trigger the handler will also alert the message The messagewill display twice because the handler has been bound to the change event on both of theform elements

        As of jQuery 14 the change event bubbles in Internet Explorer behaving consistent ly with theevent in other modern browsers

        Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw

        Javascript

        $(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) change()

        CSS

        div colorred

        HTML

        ltselect name=sweets multiple=multiplegt ltoptiongtChocolateltoptiongt ltoption selected=selectedgtCandyltoptiongt

        ltoptiongtTaffyltoptiongt ltoption selected=selectedgtCaramelltoptiongt ltoptiongtFudgeltoptiongt ltoptiongtCookieltoptiongt

        ltselectgt ltdivgtltdivgt

        Example 2 To add a validity test to all text input elements

        Javascript

        $(input[type=text])change( function() check input ($(this)val()) for validity here)

        blur

        Bind an event handler to the blur JavaScript event or t rigger that event on an element

        Added in version 10

        blur()jQuery

        This method is a shortcut for bind(blur handler) in the f irst two variat ions and t rigger(blur) inthe third

        The blur event is sent to an element when it loses focus Originally this event was only

        applicable to form elements such as ltinputgt In recent browsers the domain of the event hasbeen extended to include all element types An element can lose focus via keyboardcommands such as the Tab key or by mouse clicks elsewhere on the page

        For example consider the HTML

        ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgtThe event handler can be bound to the first input field$(target)blur(function() alert(Handler for blur() called))

        Now if the f irst f ield has the focus clicking elsewhere or tabbing away from it displays the alert

        Handler for blur() called

        To trigger the event programmatically apply blur() without an argument

        $(other)cl ick(function() $(target)blur())

        After this code executes clicks on Trigger the handler will also alert the message

        The blur event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the blur event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping blur to the focusout event in its eventdelegat ion methods live() and delegate()

        Example 1 To trigger the blur event on all paragraphs

        Javascript

        $(p)blur()

        focus

        Bind an event handler to the focus JavaScript event or t rigger that event on an element

        Added in version 10

        focus()jQuery

        This method is a shortcut for bind(focus handler) in the f irst and second variat ionsand t rigger(focus) in the third

        The focus event is sent to an element when it gains focus This event is implicit lyapplicable to a limited set of elements such as form elements (ltinputgt ltselectgt etc) andlinks (lta hrefgt) In recent browser versions the event can be extended to include allelement types by explicit ly set t ing the element s tabindex property An element can gainfocus via keyboard commands such as the Tab key or by mouse clicks on the element

        Elements with focus are usually highlighted in some way by the browser for examplewith a dotted line surrounding the element The focus is used to determine which elementis the f irst to receive keyboard-related events

        For example consider the HTML

        ltformgt ltinput id=target type=text value=Field 1 gt ltinput type=text value=Field 2 gtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the f irst input f ield

        $(target)focus(function() alert(Handler for focus() called))

        Now clicking on the f irst f ield or tabbing to it f rom another f ield displays the alert

        Handler for focus() called

        We can trigger the event when another element is clicked

        $(other)cl ick(function() $(target)focus())

        After this code executes clicks on Trigger the handler will also alert the message

        The focus event does not bubble in Internet Explorer Therefore scripts that rely on eventdelegat ion with the focus event will not work consistent ly across browsers As of version 142however jQuery works around this limitat ion by mapping focus to the focusin event in its event

        delegat ion methods live() and delegate()

        Triggering the focus on hidden elements causes an error in Internet ExplorerTake care to only call focus() without parameters on elements that are visible

        Example 1 Fire focus

        CSS

        span displaynone

        Javascript

        $(input)focus(function () $(this)next(span)css(display inl ine)fadeOut(1000) )

        HTML

        ltpgtltinput type=text gt ltspangtfocus fireltspangtltpgt

        ltpgtltinput type=password gt ltspangtfocus fireltspangtltpgt

        Example 2 To stop people f rom writ ing in text input boxes t ry

        Javascript

        $(input[type=text])focus(function() $(this)blur())

        Example 3 To focus on a login input box with id login on page startup t ry

        Javascript

        $(document)ready(function() $(login)focus())

        serializeArray

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

        Added in version 12

        serializeArray()Array

        The serializeArray() method creates a JavaScript array of objects ready to be encoded as aJSON string It operates on a jQuery object represent ing a set of form elements The formelements can be of several types

        ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

        The serializeArray() method uses the standard W3C rules for successful controls to determinewhich elements it should include in part icular the element cannot be disabled and must containa name attribute No submit button value is serialized since the form was not submit ted using abutton Data f rom f ile select elements is not serialized

        This method can act on a jQuery object that has selected individual form elements such asltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgt tag itselffor serializat ion

        $(form)submit(function() consolelog($(this)serial izeArray()) return false)

        This produces the following data structure (provided that the browser supports consolelog)

        [ name a value 1 name b value 2 name c value 3 name d value 4 name e value 5 ]

        Example 1 Get the values from a form iterate through them and append them to a resultsdisplay

        Javascript

        function showValues() var fields = $(input)serial izeArray() $(results)empty() jQueryeach(fields function(i field) $(results)append(fieldvalue + ) )

        $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

        CSS

        body select font-size14px form margin5px p colorred margin5px b colorblue

        HTML

        ltpgtltbgtResultsltbgt ltspan id=resultsgtltspangtltpgt

        ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt

        ltselectgt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

        ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

        ltlabel for=ch1gtcheck1ltlabelgt ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

        ltlabel for=ch2gtcheck2ltlabelgt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

        ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

        ltlabel for=r2gtradio2ltlabelgt ltformgt

        serialize

        Encode a set of form elements as a string for submission

        Added in version 10

        serialize()String

        The serialize() method creates a text string in standard URL-encoded notat ion It operates ona jQuery object represent ing a set of form elements The form elements can be of severaltypes

        ltformgt ltdivgtltinput type=text name=a value=1 id=a gtltdivgt ltdivgtltinput type=text name=b value=2 id=b gtltdivgt ltdivgtltinput type=hidden name=c value=3 id=c gtltdivgt ltdivgt lttextarea name=d rows=8 cols=40gt4lttextareagt ltdivgt ltdivgtltselect name=egt ltoption value=5 selected=selectedgt5ltoptiongt ltoption value=6gt6ltoptiongt ltoption value=7gt7ltoptiongt ltselectgtltdivgt ltdivgt ltinput type=checkbox name=f value=8 id=f gt ltdivgt ltdivgt ltinput type=submit name=g value=Submit id=g gt ltdivgtltformgt

        The serialize() method can act on a jQuery object that has selected individual form elementssuch as ltinputgt lttextareagt and ltselectgt However it is typically easier to select the ltformgttag itself for serializat ion

        $(form)submit(function() alert($(this)serial ize()) return false)

        This produces a standard-looking query string

        a=1ampb=2ampc=3ampd=4ampe=5

        Warning select ing both the form and its children will cause duplicates in the serialized string

        Note Only successful controls are serialized to the string No submit button value is serializedsince the form was not submit ted using a button For a form element s value to be included inthe serialized string the element must have a name attribute Values from checkboxes andradio buttons (inputs of type radio or checkbox) are included only if they are checked Datafrom f ile select elements is not serialized

        Example 1 Serialize a form to a query string that could be sent to a server in an Ajax request

        Javascript

        function showValues() var str = $(form)serial ize() $(results)text(str) $(checkbox radio)cl ick(showValues) $(select)change(showValues) showValues()

        CSS

        body select font-size12px form margin5px p colorred margin5px font-size14px b colorblue

        HTML

        ltformgt ltselect name=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt

        ltbr gt ltselect name=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt

        ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=check value=check1 id=ch1gt

        ltlabel for=ch1gtcheck1ltlabelgt

        ltinput type=checkbox name=check value=check2 checked=checked id=ch2gt

        ltlabel for=ch2gtcheck2ltlabelgtltbr gt ltinput type=radio name=radio value=radio1 checked=checked id=r1gt

        ltlabel for=r1gtradio1ltlabelgt ltinput type=radio name=radio value=radio2 id=r2gt

        ltlabel for=r2gtradio2ltlabelgt ltformgt ltpgtlttt id=resultsgtltttgtltpgt

        jQueryparam

        Create a serialized representat ion of an array or object suitable for use in a URL query string orAjax request

        Added in version 14

        jQueryparam(obj t radit ional)String

        objArray Object An array or object to serialize

        t radit ionalBoolean A Boolean indicat ing whether to perform a tradit ional shallowserializat ion

        This funct ion is used internally to convert form element values into a serialized stringrepresentat ion (See serialize() for more informat ion)

        As of jQuery 13 the return value of a funct ion is used instead of the funct ion as a String

        As of jQuery 14 the $param() method serializes deep objects recursively to accommodatemodern script ing languages and frameworks such as PHP and Ruby on Rails You can disablethis funct ionality globally by sett ing jQueryajaxSett ingst radit ional = t rue

        If the object passed is in an Array it must be an array of objects in the format returned byserializeArray()

        [namefirstvalueRicknamelastvalueAstleynamejobvalueRock Star]

        Note Because some frameworks have limited ability to parse serialized arraysdevelopers should exercise caution when passing an obj argument that containsobjects or arrays nested within another array

        Note Because there is no universally agreed-upon specification for param stringsit is not possible to encode complex data structures using this method in a mannerthat works ideally across all languages supporting such input Until such time thatthere is the $param method will remain in its current form

        In jQuery 14 HTML5 input elements are also serialized

        We can display a query string representat ion of an object and a URI-decoded version of the

        same as follows

        var myObject = a one 1 two 2 three 3 b [123]var recursiveEncoded = $param(myObject)var recursiveDecoded = decodeURIComponent($param(myObject))

        alert(recursiveEncoded)alert(recursiveDecoded)

        The values of recursiveEncoded and recursiveDecoded are alerted as follows

        a5Bone5D=1ampa5Btwo5D=2ampa5Bthree5D=3ampb5B5D=1ampb5B5D=2ampb5B5D=3

        a[one]=1ampa[two]=2ampa[three]=3ampb[]=1ampb[]=2ampb[]=3

        To emulate the behavior of $param() prior to jQuery 14 we can set the t radit ional argument totrue

        var myObject = a one 1 two 2 three 3 b [123]var shallowEncoded = $param(myObject true)var shallowDecoded = decodeURIComponent(shallowEncoded)

        alert(shallowEncoded)alert(shallowDecoded)

        The values of shallowEncoded and shallowDecoded are alerted as follows

        a=5Bobject+Object5Dampb=1ampb=2ampb=3

        a=[object+Object ]ampb=1ampb=2ampb=3

        Example 1 Serialize a keyvalue object

        Javascript

        var params = width1680 height1050 var str = jQueryparam(params) $(results)text(str)

        CSS

        div colorred

        HTML

        ltdiv id=resultsgtltdivgt

        Example 2 Serialize a few complex objects

        Javascript

        lt=132 $param( a [234] ) a=2ampa=3ampa=4 gt=14$param( a [234] ) a[]=2ampa[]=3ampa[]=4

        lt=132 $param( a b1c2 d [34 e5 ] ) a=[object+Object]ampd=3ampd=4ampd=[object+Object] gt=14 $param( a b1c2 d [34 e5 ] ) a[b]=1ampa[c]=2ampd[]=3ampd[]=4ampd[2][e]=5

        CSS

        div colorred

        val see Attributes

        val see Attributes

        Events

        toggle

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

        Added in version 10

        toggle(handler(eventObject) handler(eventObject) handler(eventObject))jQuery

        handler(eventObject)Funct ion A funct ion to execute every even t ime the element isclicked

        handler(eventObject)Funct ion A funct ion to execute every odd t ime the element isclicked

        handler(eventObject)Funct ion (opt ional) Addit ional handlers to cycle through af terclicks

        The toggle() method binds a handler for the click event so the rules out lined for the t riggeringof click apply here as well

        For example consider the HTMLltdiv id=targetgt Click hereltdivgt

        Event handlers can then bebound to the ltdivgt

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

        First handler for toggle() called

        Second handler for toggle() called

        First handler for toggle() called

        Second handler for toggle() called

        First handler for toggle() called

        If more than two handlers are provided toggle() will cycle among all of them For example ifthere are three handlers then the f irst handler will be called on the f irst click the fourth clickthe seventh click and so on

        Note jQuery also provides an animation method named toggle() that toggles the

        visibility of elements Whether the animation or the event method is fired dependson the set of arguments passed

        The toggle() method is provided for convenience It is relat ively straightforward to implementthe same behavior by hand and this can be necessary if the assumptions built into toggle()prove limit ing For example toggle() is not guaranteed to work correct ly if applied twice to thesame element Since toggle() internally uses a click handler to do its work we must unbind clickto remove a behavior at tached with toggle() so other click handlers can be caught in thecrossf ire The implementat ion also calls preventDefault () on the event so links will not befollowed and buttons will not be clicked if toggle() has been called on the element

        Example 1 Click to toggle highlight on the list item

        Javascript

        $(l i)toggle( function () $(this)css(list-style-typedisc colorblue) function () $(this)css(list-style-typedisc colorred) function () $(this)css(list-style-type color) )

        CSS

        ul margin10px l ist-styleinside circle font-weightbold l i cursorpointer

        HTML

        ltulgt ltligtGo to the storeltligt ltligtPick up dinnerltligt ltligtDebug crashltligt

        ltligtTake a jogltligt ltulgt

        Example 2 To toggle a style on table cells

        Javascript

        Javascript

        $(td)toggle( function () $(this)addClass(selected) function () $(this)removeClass(selected) )

        eventnamespace

        The namespace specif ied when the event was triggered

        Added in version 143

        This will likely be used primarily by plugin authors who wish to handle tasks dif ferent lydepending on the event namespace used

        Example 1 Determine the event namespace used

        Javascript

        $(p)bind(testsomething function(event) alert( eventnamespace ))$(button)cl ick(function(event) $(p)trigger(testsomething))

        HTML

        ltbuttongtdisplay eventnamespaceltbuttongtltpgtltpgt

        undelegate

        Remove a handler f rom the event for all elements which match the current selector now or inthe future based upon a specif ic set of root elements

        Added in version 16

        undelegate(namespace)jQuery

        namespaceString A string containing a namespace to unbind all events f rom

        Undelegate is a way of removing event handlers that have been bound using delegate() Itworks virtually ident ically to die() with the addit ion of a selector f ilter argument (which isrequired for delegat ion to work)

        Example 1 Can bind and unbind events to the colored button

        Javascript

        function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(body)delegate(theone cl ick aClick) find(theone)text(Can Click))$(unbind)cl ick(function () $(body)undelegate(theone cl ick aClick) find(theone)text(Does nothing))

        CSS

        button margin5px buttontheone colorred backgroundyellow

        HTML

        ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongtltdiv style=displaynonegtClickltdivgt

        Example 2 To unbind all delegated events f rom all paragraphs write

        Javascript

        $(p)undelegate()

        Example 3 To unbind all delegated click events f rom all paragraphs write

        Javascript

        $(p)undelegate( cl ick )

        Example 4 To undelegate just one previously bound handler pass the funct ion in as the third

        argument

        Javascript

        var foo = function () code to handle some kind of event

        now foo wil l be called when paragraphs are cl icked $(body)delegate(p cl ick foo)

        foo wil l no longer be called$(body)undelegate(p cl ick foo)

        Example 5 To unbind all delegated events by their namespace

        Javascript

        var foo = function () code to handle some kind of event

        delegate events under the whatever namespace$(form)delegate(button cl ickwhatever foo)

        $(form)delegate(input[type=text] keypresswhatever foo)

        unbind all events delegated under the whatever namespace

        $(form)undelegate(whatever)

        delegate

        Attach a handler to one or more events for all elements that match the selector now or in thefuture based on a specif ic set of root elements

        Added in version 143

        delegate(selector events)jQuery

        selectorString A selector to f ilter the elements that t rigger the event

        eventsMap A map of one or more event types and funct ions to execute for them

        Delegate is an alternat ive to using the live() method allowing for each binding of eventdelegat ion to specif ic DOM elements For example the following delegate code

        $(table)delegate(td hover function() $(this)toggleClass(hover))

        Is equivalent to the following code writ ten using live()

        $(table)each(function() $(td this)l ive(hover function() $(this)toggleClass(hover) ))

        See also the undelegate() method for a way of removing event handlers added in delegate()

        Passing and handling event data works the same way as it does for bind()

        Example 1 Click a paragraph to add another Note that delegate() binds the click event to allparagraphs - even new ones

        Javascript

        $(body)delegate(p cl ick function() $(this)after(ltpgtAnother paragraphltpgt) )

        CSS

        p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

        HTML

        ltpgtClick meltpgt

        ltspangtltspangt

        Example 2 To display each paragraphs text in an alert box whenever it is clicked

        Javascript

        $(body)delegate(p cl ick function() alert( $(this)text() ))

        Example 3 To cancel a default act ion and prevent it f rom bubbling up return false

        Javascript

        $(body)delegate(a cl ick function() return false )

        Example 4 To cancel only the default act ion by using the preventDefault method

        Javascript

        $(body)delegate(a cl ick function(event) eventpreventDefault())

        Example 5 Can bind custom events too

        Javascript

        $(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)cl ick(function () $(p)trigger(myCustomEvent) )

        CSS

        p colorred span colorblue

        HTML

        ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

        jQueryproxy

        Takes a funct ion and returns a new one that will always have a part icular context

        Added in version 14

        jQueryproxy(context name)Funct ion

        context Object The object to which the context of the funct ion should be set

        nameString The name of the funct ion whose context will be changed (should be aproperty of the context object)

        This method is most useful for at taching event handlers to an element where the context ispoint ing back to a dif ferent object Addit ionally jQuery makes sure that even if you bind thefunct ion returned from jQueryproxy() it will st ill unbind the correct funct ion if passed theoriginal

        Example 1 Change the context of funct ions bound to a click handler using the funct ioncontext signature Unbind the f irst handler af ter f irst click

        HTML

        ltpgtltbutton type=button id=testgtTestltbuttongtltpgtltdiv id=loggtltdivgt

        Javascript

        var me = type zombie test function(event) Without proxy `this` would refer to the event target use eventtarget to reference that element var element = eventtarget $(element)css(background-color red)

        With proxy `this` refers to the me object encapsulating this function $(log)append( Hello + thistype + ltbrgt ) $(test)unbind(click thistest)

        var you = type person test function(event) $(log)append( thistype + )

        execute youtest() in the context of the `you` object no matter where it is called i e the `this` keyword wil l refer to `you`var youClick = $proxy( youtest you )

        attach click handlers to test$(test) this === zombie handler unbound after first cl ick cl ick( $proxy( metest me ) ) this === person cl ick( youClick ) this === zombie cl ick( $proxy( youtest me ) ) this === ltbuttongt element cl ick( youtest )

        Example 2 Enforce the context of the funct ion using the context funct ion name signatureUnbind the handler af ter f irst click

        HTML

        ltpgtltbutton id=testgtTestltbuttongtltpgt ltp id=loggtltpgt

        Javascript

        var obj = name John test function() $(log)append( thisname ) $(test)unbind(click objtest)

        $(test)cl ick( jQueryproxy( obj test ) )

        focusout

        Bind an event handler to the focusout JavaScript event

        Added in version 143

        focusout(eventData handler(eventObject))jQuery

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

        This method is a shortcut for bind(focusout handler)

        The focusout event is sent to an element when it or any element inside of it loses focus Thisis dist inct f rom the blur event in that it supports detect ing the loss of focus from parentelements (in other words it supports event bubbling)

        This event will likely be used together with the focusin event

        Example 1 Watch for a loss of focus to occur inside paragraphs and note the dif ferencebetween the focusout count and the blur count

        CSS

        inputs float left margin-right 1em

        inputs p margin-top 0

        Javascript

        var fo = 0 b = 0$(p)focusout(function() fo++ $(fo) text(focusout fired + fo + x))blur(function() b++ $(b) text(blur fired + b + x) )

        HTML

        ltdiv class=inputsgt ltpgt ltinput type=text gtltbr gt ltinput type=text gt ltpgt ltpgt ltinput type=password gt ltpgtltdivgtltdiv id=fogtfocusout fireltdivgtltdiv id=bgtblur fireltdivgt

        focusin

        Bind an event handler to the focusin JavaScript event

        Added in version 143

        focusin(eventData handler(eventObject))jQuery

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

        This method is a shortcut for bind(focusin handler)

        The focusin event is sent to an element when it or any element inside of it gains focus This isdist inct f rom the focus event in that it supports detect ing the focus event on parent elements(in other words it supports event bubbling)

        This event will likely be used together with the focusout event

        Example 1 Watch for a focus to occur within the paragraphs on the page

        CSS

        span displaynone

        Javascript

        $(p)focusin(function() $(this)find(span)css(display inl ine)fadeOut(1000) )

        HTML

        ltpgtltinput type=text gt ltspangtfocusin fireltspangtltpgtltpgtltinput type=password gt ltspangtfocusin fireltspangtltpgt

        eventisImmediatePropagationStopped

        Returns whether eventstopImmediatePropagat ion() was ever called on this event object

        Added in version 13

        eventisImmediatePropagat ionStopped()Boolean

        This property was introduced in DOM level 3

        Example 1 Checks whether eventstopImmediatePropagat ion() was called

        Javascript

        function immediatePropStopped(e) var msg = i f ( eisImmediatePropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

        $(button)cl ick(function(event) immediatePropStopped(event) eventstopImmediatePropagation() immediatePropStopped(event))

        HTML

        ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

        eventstopImmediatePropagation

        Keeps the rest of the handlers f rom being executed and prevents the event f rom bubbling upthe DOM tree

        Added in version 13

        eventstopImmediatePropagat ion()

        In addit ion to keeping any addit ional handlers on an element f rom being executed this methodalso stops the bubbling by implicit ly calling eventstopPropagat ion() To simply prevent theevent f rom bubbling to ancestor elements but allow other event handlers to execute on thesame element we can use eventstopPropagat ion() instead

        Use eventisImmediatePropagat ionStopped() to know whether this method was ever called (onthat event object)

        Example 1 Prevents other event handlers f rom being called

        CSS

        p height 30px width 150px background-color ccf div height 30px width 150px background-color cfc

        Javascript

        $(p)cl ick(function(event) eventstopImmediatePropagation())$(p)cl ick(function(event) This function wont be executed $(this)css(background-color f00)) $(div)cl ick(function(event) This function wil l be executed $(this)css(background-color f00))

        HTML

        ltpgtparagraphltpgtltdivgtdivisionltdivgt

        eventisPropagationStopped

        Returns whether eventstopPropagat ion() was ever called on this event object

        Added in version 13

        eventisPropagat ionStopped()Boolean

        This event method is described in the W3C DOM Level 3 specif icat ion

        Example 1 Checks whether eventstopPropagat ion() was called

        Javascript

        function propStopped(e) var msg = i f ( eisPropagationStopped() ) msg = called else msg = not called $(stop-log)append( ltdivgt + msg + ltdivgt )

        $(button)cl ick(function(event) propStopped(event) eventstopPropagation() propStopped(event))

        HTML

        ltbuttongtclick meltbuttongt ltdiv id=stop-loggtltdivgt

        eventstopPropagation

        Prevents the event f rom bubbling up the DOM tree prevent ing any parent handlers f rom beingnot if ied of the event

        Added in version 10

        eventstopPropagat ion()

        We can use eventisPropagat ionStopped() to determine if this method was ever called (on thatevent object)

        This method works for custom events t riggered with t rigger() as well

        Note that this will not prevent other handlers on the same element f rom running

        Example 1 Kill the bubbling on the click event

        Javascript

        $(p)cl ick(function(event) eventstopPropagation() do something)

        eventisDefaultPrevented

        Returns whether eventpreventDefault () was ever called on this event object

        Added in version 13

        eventisDefaultPrevented()Boolean

        Example 1 Checks whether eventpreventDefault () was called

        Javascript

        $(a)cl ick(function(event) alert( eventisDefaultPrevented() ) false eventpreventDefault() alert( eventisDefaultPrevented() ) true)

        eventpreventDefault

        If this method is called the default act ion of the event will not be triggered

        Added in version 10

        eventpreventDefault ()undef ined

        For example clicked anchors will not take the browser to a new URL We can useeventisDefaultPrevented() to determine if this method has been called by an event handlerthat was triggered by this event

        Example 1 Cancel the default act ion (navigat ion) of the click

        Javascript

        $(a)cl ick(function(event) eventpreventDefault() $(ltdivgt) append(default + eventtype + prevented) appendTo(log))

        HTML

        lta href=httpjquerycomgtdefault cl ick action is preventedltagtltdiv id=loggtltdivgt

        eventtimeStamp

        The dif ference in milliseconds between the t ime an event is t riggered and January 1 1970

        Added in version 126

        This property can be useful for prof iling the performance of certain jQuery funct ions by gett ingthe eventt imeStamp value at two points in the code and not ing the dif ference

        Example 1 Display the t ime since the click handler last executed

        CSS

        div height 100px width 300px margin 10px background-color ffd overflow auto

        Javascript

        var last diff$(div)cl ick(function(event) if ( last ) diff = eventtimeStamp - last $(div)append(time since last event + diff + ltbrgt) else $(div)append(Click againltbrgt) last = eventtimeStamp)

        HTML

        ltdivgtClickltdivgt

        eventresult

        The last value returned by an event handler that was triggered by this event unless the valuewas undef ined

        Added in version 13

        This property can be useful for gett ing previous return values of custom events

        Example 1 Display previous handlers return value

        Javascript

        $(button)cl ick(function(event) return hey)$(button)cl ick(function(event) $(p)html( eventresult ))

        HTML

        ltbuttongtdisplay eventresultltbuttongtltpgtltpgt

        eventwhich

        For key or button events this at t ribute indicates the specif ic button or key that was pressed

        Added in version 113

        eventwhich normalizes eventkeyCode and eventcharCode It is recommended to watcheventwhich for keyboard key input For more detail read about eventcharCode on the MDC

        Example 1 Log what key was depressed

        Javascript

        $(whichkey)bind(keydownfunction(e) $(log)html(etype + + ewhich ))

        HTML

        ltinput id=whichkey value=type somethinggtltdiv id=loggtltdivgt

        Results

        keydown 74

        eventpageY

        The mouse posit ion relat ive to the top edge of the document

        Added in version 104

        Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthis if rame)

        CSS

        body background-color eef div padding 20px

        HTML

        ltdiv id=loggtltdivgt

        Javascript

        $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

        eventpageX

        The mouse posit ion relat ive to the lef t edge of the document

        Added in version 104

        Example 1 Show the mouse posit ion relat ive to the lef t and top edges of the document (withinthe if rame)

        CSS

        body background-color eef div padding 20px

        HTML

        ltdiv id=loggtltdivgt

        Javascript

        $(document)bind(mousemovefunction(e) $(log)text(epageX + epageX + epageY + epageY) )

        eventcurrentTarget

        The current DOM element within the event bubbling phase

        Added in version 13

        This property will typically be equal to the this of the funct ion

        If you are using jQueryproxy or another form of scope manipulation this will be equal towhatever context you have provided not eventcurrentTarget

        Example 1 Alert that currentTarget matches the `this` keyword

        Javascript

        $(p)cl ick(function(event) alert( eventcurrentTarget === this ) true)

        eventrelatedTarget

        The other DOM element involved in the event if any

        Added in version 114

        For mouseout indicates the element being entered for mouseover indicates the elementbeing exited

        Example 1 On mouseout of anchors alert the element type being entered

        Javascript

        $(a)mouseout(function(event) alert(eventrelatedTargetnodeName) DIV)

        eventdata

        The opt ional data passed to jQueryfnbind when the current execut ing handler was bound

        Added in version 11

        Example 1 The descript ion of the example

        Javascript

        $(a)each(function(i) $(this)bind(cl ick indexi function(e) alert(my index is + edataindex) ))

        eventtarget

        The DOM element that init iated the event

        Added in version 10

        The target property can be the element that registered for the event or a descendant of it It isof ten useful to compare eventtarget to this in order to determine if the event is being handleddue to event bubbling This property is very useful in event delegat ion when events bubble

        Example 1 Display the tags name on click

        Javascript

        $(body)cl ick(function(event) $(log)html(clicked + eventtargetnodeName))

        CSS

        span strong p padding 8px display block border 1px solid 999

        HTML

        ltdiv id=loggtltdivgtltdivgt ltpgt ltstronggtltspangtclickltspangtltstronggt ltpgtltdivgt

        Example 2 Implements a simple event delegat ion The click handler is added to an unorderedlist and the children of its li children are hidden Clicking one of the li children toggles (seetoggle()) their children

        Javascript

        function handler(event) var $target = $(eventtarget) i f( $targetis( l i) ) $targetchildren()toggle() $(ul)cl ick(handler)find(ul)hide()

        HTML

        ltulgt ltligtitem 1 ltulgt ltligtsub item 1-altligt ltligtsub item 1-bltligt ltulgt ltl igt ltligtitem 2 ltulgt ltligtsub item 2-altligt ltligtsub item 2-bltligt ltulgt ltl igt ltulgt

        eventtype

        Describes the nature of the event

        Added in version 10

        Example 1 On all anchor clicks alert the event type

        Javascript

        $(a)cl ick(function(event) alert(eventtype) cl ick)

        keydown

        Bind an event handler to the keydown JavaScript event or t rigger that event on an element

        Added in version 10

        keydown()jQuery

        This method is a shortcut for bind(keydown handler) in the f irst and second variat ions and

        t rigger(keydown) in the third

        The keydown event is sent to an element when the user f irst presses a key on the keyboard Itcan be at tached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

        For example consider the HTML

        ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the input f ield

        $(target)keydown(function() alert(Handler for keydown() called))

        Now when the insert ion point is inside the f ield pressing a key displays the alert

        Handler for keydown() called

        To trigger the event manually apply keydown() without an argument

        $(other)cl ick(function() $(target)keydown())

        After this code executes clicks on Trigger the handler will also alert the message

        If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

        To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

        Example 1 Show the event object for the keydown handler when a key is pressed in the input

        Javascript

        var xTriggered = 0$(target)keydown(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keydown() called + xTriggered + time(s) $print(msg html) $print(event))

        $(other)cl ick(function() $(target)keydown())

        CSS

        fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

        HTML

        ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

        scroll

        Bind an event handler to the scroll JavaScript event or t rigger that event on an element

        Added in version 10

        scroll()jQuery

        This method is a shortcut for bind(scroll handler) in the f irst and second variat ions andtrigger(scroll) in the third

        The scroll event is sent to an element when the user scrolls to a dif ferent place in the elementIt applies to window objects but also to scrollable f rames and elements with the overf low CSSproperty set to scroll (or auto when the element s explicit height or width is less than the heightor width of its contents)

        For example consider the HTML

        ltdiv id=target style=overflow scroll width 200px height 100pxgt 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 al iquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt moll it anim id est laborumltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The style def init ion is present to make the target element small enough to be scrollable

        The scroll event handler can bebound to this element

        $(target)scroll(function() $(log)append(ltdivgtHandler for scroll() calledltdivgt))

        Now when the user scrolls the text up or down one or more messages are appended to ltdiv

        id=loggtltdivgt

        Handler for scroll() called

        To trigger the event manually apply scroll() without an argument

        $(other)cl ick(function() $(target)scroll())

        After this code executes clicks on Trigger the handler will also append the message

        A scroll event is sent whenever the element s scroll posit ion changes regardless of the causeA mouse click or drag on the scroll bar dragging inside the element pressing the arrow keys orusing the mouses scroll wheel could cause this event

        Example 1 To do something when your page is scrolled

        Javascript

        $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(p)clone()appendTo(documentbody) $(window)scroll(function () $(span)css(display inl ine)fadeOut(slow) )

        CSS

        div colorblue p colorgreen span colorred displaynone

        HTML

        ltdivgtTry scroll ing the iframeltdivgt ltpgtParagraph - ltspangtScroll happenedltspangtltpgt

        resize

        Bind an event handler to the resize JavaScript event or t rigger that event on an element

        Added in version 10

        resize()jQuery

        This method is a shortcut for bind(resize handler) in the f irst and second variat ions andtrigger(resize) in the third

        The resize event is sent to the window element when the size of the browser window changes

        $(window)resize(function() $(log)append(ltdivgtHandler for resize() calledltdivgt))

        Now whenever the browser windows size is changed the message is appended to ltdivid=loggt one or more t imes depending on the browser

        Code in a resize handler should never rely on the number of t imes the handler is calledDepending on implementat ion resize events can be sent cont inuously as the resizing is inprogress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safariand Chrome) or only once at the end of the resize operat ion (the typical behavior in someother browsers such as Opera)

        Example 1 To see the window width while (or af ter) it is resized t ry

        Javascript

        $(window)resize(function() $(body)prepend(ltdivgt + $(window)width() + ltdivgt))

        keyup

        Bind an event handler to the keyup JavaScript event or t rigger that event on an element

        Added in version 10

        keyup()jQuery

        This method is a shortcut for bind(keyup handler) in the f irst two variat ions andtrigger(keyup) in the third

        The keyup event is sent to an element when the user releases a key on the keyboard It can beattached to any element but the event is only sent to the element that has the focusFocusable elements can vary between browsers but form elements can always get focus soare reasonable candidates for this event type

        For example consider the HTML

        ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the input f ield

        $(target)keyup(function() alert(Handler for keyup() called))

        Now when the insert ion point is inside the f ield and a key is pressed and released the alert isdisplayed

        Handler for keyup() called

        To trigger the event manually apply keyup() without arguments

        $(other)cl ick(function() $(target)keyup())

        After this code executes clicks on Trigger the handler will also alert the message

        If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

        To determine which key was pressed examine the event object that is passed to the handlerfunct ion While browsers use dif fering propert ies to store this informat ion jQuery normalizesthe which property so you can reliably use it to retrieve the key code This code corresponds toa key on the keyboard including codes for special keys such as arrows For catching actual textentry keypress() may be a better choice

        Example 1 Show the event object for the keyup handler when a key is released in the input

        Javascript

        var xTriggered = 0$(target)keyup(function(event) if (eventkeyCode == 13) eventpreventDefault() xTriggered++ var msg = Handler for keyup() called + xTriggered + time(s) $print(msg html) $print(event))

        $(other)cl ick(function() $(target)keyup())

        CSS

        fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

        HTML

        ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript type=textjavascript src=scriptseventsjsgtltscriptgt

        keypress

        Bind an event handler to the keypress JavaScript event or t rigger that event on an element

        Added in version 10

        keypress()jQuery

        Note as the keypress event isnt covered by any of f icial specif icat ion the actual behaviorencountered when using it may dif fer across browsers browser versions and plat forms

        This method is a shortcut for bind(keypress handler) in the f irst two variat ions andtrigger(keypress) in the third

        The keypress event is sent to an element when the browser registers keyboard input This issimilar to the keydown event except in the case of key repeats If the user presses and holds akey a keydown event is t riggered once but separate keypress events are t riggered for eachinserted character In addit ion modif ier keys (such as Shif t ) t rigger keydown events but notkeypress events

        A keypress event handler can be at tached to any element but the event is only sent to theelement that has the focus Focusable elements can vary between browsers but formelements can always get focus so are reasonable candidates for this event type

        For example consider the HTML

        ltformgt ltfieldsetgt ltinput id=target type=text value=Hello there gt ltfieldsetgtltformgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be bound to the input f ield

        $(target)keypress(function() alert(Handler for keypress() called))

        Now when the insert ion point is inside the f ield pressing a key displays the alert

        Handler for keypress() called

        The message repeats if the key is held down To trigger the event manually apply keypress()without an argument

        $(other)cl ick(function() $(target)keypress())

        After this code executes clicks on Trigger the handler will also alert the message

        If key presses anywhere need to be caught (for example to implement global shortcut keys ona page) it is useful to at tach this behavior to the document object Because of event bubblingall key presses will make their way up the DOM to the document object unless explicit lystopped

        To determine which character was entered examine the event object that is passed to thehandler funct ion While browsers use dif fering propert ies to store this informat ion jQuerynormalizes the which property so you can reliably use it to retrieve the character code

        Note that keydown and keyup provide a code indicat ing which key is pressed while keypressindicates which character was entered For example a lowercase a will be reported as 65 bykeydown and keyup but as 97 by keypress An uppercase A is reported as 65 by all eventsBecause of this dist inct ion when catching special keystrokes such as arrow keys keydown() orkeyup() is a better choice

        Example 1 Show the event object when a key is pressed in the input Note This demo relies ona simple $print() plugin (ht tpapijquerycomscriptseventsjs) for the event object s output

        Javascript

        var xTriggered = 0$(target)keypress(function(event) if ( eventwhich == 13 ) eventpreventDefault() xTriggered++ var msg = Handler for keypress() called + xTriggered + time(s) $print( msg html ) $print( event ))

        $(other)cl ick(function() $(target)keypress())

        CSS

        fieldset margin-bottom 1em input display block margin-bottom 25em print-output width 100print-output-l ine white-space pre padding 5px font-family monaco monospace font-size 7em

        HTML

        ltformgt ltfieldsetgt ltlabel for=targetgtType Somethingltlabelgt ltinput id=target type=text gt ltfieldsetgtltformgtltbutton id=othergt Trigger the handlerltbuttongtltscript src=httpapijquerycomscriptseventsjsgtltscriptgt

        submit see Forms

        select see Forms

        change see Forms

        blur see Forms

        focus see Forms

        mousemove

        Bind an event handler to the mousemove JavaScript event or t rigger that event on anelement

        Added in version 10

        mousemove()jQuery

        This method is a shortcut for bind(mousemove handler) in the f irst two variat ions andtrigger(mousemove) in the third

        The mousemove event is sent to an element when the mouse pointer moves inside theelement Any HTML element can receive this event

        For example consider the HTML

        ltdiv id=targetgt Move hereltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The event handler can be bound to the target

        $(target)mousemove(function(event) var msg = Handler for mousemove() called at msg += eventpageX + + eventpageY $(log)append(ltdivgt + msg + ltdivgt))

        Now when the mouse pointer moves within the target button the messages are appended toltdiv id=loggt

        Handler for mousemove() called at (399 48)

        Handler for mousemove() called at (398 46)

        Handler for mousemove() called at (397 44)

        Handler for mousemove() called at (396 42)

        To trigger the event manually apply mousemove() without an argument

        $(other)cl ick(function() $(target)mousemove())

        After this code executes clicks on the Trigger button will also append the message

        Handler for mousemove() called at (undef ined undef ined)

        When tracking mouse movement you usually need to know the actual posit ion of the mousepointer The event object that is passed to the handler contains some informat ion about themouse coordinates Propert ies such as clientX of fsetX and pageX are available but supportfor them dif fers between browsers Fortunately jQuery normalizes the pageX and pageYpropert ies so that they can be used in all browsers These propert ies provide the X and Ycoordinates of the mouse pointer relat ive to the top-lef t corner of the document as illustratedin the example output above

        Keep in mind that the mousemove event is t riggered whenever the mouse pointer moves evenfor a pixel This means that hundreds of events can be generated over a very small amount oft ime If the handler has to do any signif icant processing or if mult iple handlers for the eventexist this can be a serious performance drain on the browser It is important therefore toopt imize mousemove handlers as much as possible and to unbind them as soon as they areno longer needed

        A common pattern is to bind the mousemove handler f rom within a mousedown hander and tounbind it f rom a corresponding mouseup handler If implement ing this sequence of eventsremember that the mouseup event might be sent to a dif ferent HTML element than themousemove event was To account for this the mouseup handler should typically be bound toan element high up in the DOM tree such as ltbodygt

        Example 1 Show the mouse coordinates when the mouse is moved over the yellow divCoordinates are relat ive to the window which in this case is the if rame

        Javascript

        $(div)mousemove(function(e) var pageCoords = ( + epageX + + epageY + ) var cl ientCoords = ( + ecl ientX + + ecl ientY + ) $(spanfirst)text(( epageX epageY ) - + pageCoords) $(spanlast)text(( ecl ientX ecl ientY ) - + clientCoords) )

        CSS

        div width220px height170px margin10px margin-right50px backgroundyellow border2px groove floatright p margin0 margin-left10px colorred width220px height120px padding-top70px floatleft font-size14px span displayblock

        HTML

        ltpgt Try scroll ing too ltspangtMove the mouse over the divltspangt ltspangtampnbspltspangt ltpgt

        ltdivgtltdivgt

        hover

        Bind two handlers to the matched elements to be executed when the mouse pointer entersand leaves the elements

        Added in version 10

        hover(handlerIn(eventObject) handlerOut(eventObject))jQuery

        handlerIn(eventObject)Funct ion A funct ion to execute when the mouse pointerenters the element

        handlerOut(eventObject)Funct ion A funct ion to execute when the mouse pointerleaves the element

        The hover() method binds handlers for both mouseenter and mouseleave events You can useit to simply apply behavior to an element during the t ime the mouse is within the element

        Calling $(selector)hover(handlerIn handlerOut) is shorthand for

        $(selector)mouseenter(handlerIn)mouseleave(handlerOut)

        See the discussions for mouseenter() and mouseleave() for more details

        Example 1 To add a special style to list items that are being hovered over t ry

        Javascript

        $(l i)hover( function () $(this)append($(ltspangt ltspangt)) function () $(this)find(spanlast)remove() )

        l i with fade class$(l i fade)hover(function()$(this)fadeOut(100)$(this)fadeIn(500))

        CSS

        ul margin-left20px colorblue l i cursordefault span colorred

        HTML

        ltulgt ltligtMilkltligt ltligtBreadltligt ltli class=fadegtChipsltligt

        ltli class=fadegtSocksltligt ltulgt

        Example 2 To add a special style to table cells that are being hovered over t ry

        Javascript

        $(td)hover( function () $(this)addClass(hover) function () $(this)removeClass(hover) )

        Example 3 To unbind the above example use

        Javascript

        $(td)unbind(mouseenter mouseleave)

        hover

        Bind a single handler to the matched elements to be executed when the mouse pointer entersor leaves the elements

        Added in version 14

        hover(handlerInOut(eventObject))jQuery

        handlerInOut(eventObject)Funct ion A funct ion to execute when the mouse pointerenters or leaves the element

        The hover() method when passed a single funct ion will execute that handler for bothmouseenter and mouseleave events This allows the user to use jQuerys various togglemethods within the handler or to respond dif ferent ly within the handler depending on theeventtype

        Calling $(selector)hover(handlerInOut) is shorthand for

        $(selector)bind(mouseenter mouseleave handlerInOut)

        See the discussions for mouseenter() and mouseleave() for more details

        Example 1 Slide the next sibling LI up or down on hover and toggle a class

        Javascript

        $(l i)fi lter(odd)hide() end()fi lter(even)hover( function () $(this)toggleClass(active) next()stop(true true)sl ideToggle() )

        CSS

        ul margin-left20px colorblue l i cursordefault l i active backgroundblackcolorwhite span colorred

        HTML

        ltulgt ltligtMilkltligt ltligtWhiteltligt ltligtCarrotsltligt ltligtOrangeltligt ltligtBroccoliltl igt ltligtGreenltligt ltulgt

        mouseleave

        Bind an event handler to be f ired when the mouse leaves an element or t rigger that handler onan element

        Added in version 10

        mouseleave()jQuery

        This method is a shortcut for bind(mouseleave handler) in the f irst two variat ions andtrigger(mouseleave) in the third

        The mouseleave JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer leaves the element Any HTML elementcan receive this event

        For example consider the HTML

        ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The event handler can be boundto any element

        $(outer)mouseleave(function() $(log)append(ltdivgtHandler for mouseleave() calledltdivgt))

        Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

        $(other)cl ick(function() $(outer)mouseleave())

        After this code executes clicks on Trigger the handler will also append the message

        The mouseleave event dif fers f rom mouseout in the way it handles event bubbling If mouseoutwere used in this example then when the mouse pointer moved out of the Inner element thehandler would be triggered This is usually undesirable behavior The mouseleave event on theother hand only t riggers its handler when the mouse leaves the element it is bound to not adescendant So in this example the handler is t riggered when the mouse leaves the Outerelement but not the Inner element

        Example 1 Show number of t imes mouseout and mouseleave events are t riggered mouseoutf ires when the pointer moves out of child element as well while mouseleave f ires only when thepointer moves out of the bound element

        CSS

        divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

        Javascript

        var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) )mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )

        var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) )mouseleave(function() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

        HTML

        ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        mouseenter

        Bind an event handler to be f ired when the mouse enters an element or t rigger that handler onan element

        Added in version 10

        mouseenter()jQuery

        This method is a shortcut for bind(mouseenter handler) in the f irst two variat ions andtrigger(mouseenter) in the third

        The mouseenter JavaScript event is proprietary to Internet Explorer Because of the event sgeneral ut ility jQuery simulates this event so that it can be used regardless of browser Thisevent is sent to an element when the mouse pointer enters the element Any HTML elementcan receive this event

        For example consider the HTML

        ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The event handler can be boundto any element

        $(outer)mouseenter(function() $(log)append(ltdivgtHandler for mouseenter() calledltdivgt))

        Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt You can also t rigger the event when another element is clicked

        $(other)cl ick(function() $(outer)mouseenter())

        After this code executes clicks on Trigger the handler will also append the message

        The mouseenter event dif fers f rom mouseover in the way it handles event bubbling Ifmouseover were used in this example then when the mouse pointer moved over the Innerelement the handler would be triggered This is usually undesirable behavior The mouseenterevent on the other hand only t riggers its handler when the mouse enters the element it isbound to not a descendant So in this example the handler is t riggered when the mouse entersthe Outer element but not the Inner element

        Example 1 Show texts when mouseenter and mouseout event t riggering mouseover f ireswhen the pointer moves into the child element as well while mouseenter f ires only when thepointer moves into the bound element

        CSS

        divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

        Javascript

        var i = 0 $(divoverout)mouseover(function() $(pfirstthis)text(mouse over) $(plastthis)text(++i) )mouseout(function() $(pfirstthis)text(mouse out) )

        var n = 0 $(diventerleave)mouseenter(function() $(pfirstthis)text(mouse enter) $(plastthis)text(++n) )mouseleave(function() $(pfirstthis)text(mouse leave) )

        HTML

        ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        mouseout

        Bind an event handler to the mouseout JavaScript event or t rigger that event on an element

        Added in version 10

        mouseout()jQuery

        This method is a shortcut for bind(mouseout handler) in the f irst two variat ion andtrigger(mouseout ) in the third

        The mouseout event is sent to an element when the mouse pointer leaves the element AnyHTML element can receive this event

        For example consider the HTML

        ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The event handler can be boundto any element

        $(outer)mouseout(function() $(log)append(Handler for mouseout() called))

        Now when the mouse pointer moves out of the Outer ltdivgt the message is appended to ltdivid=loggt To trigger the event manually apply mouseout() without an argument

        $(other)cl ick(function() $(outer)mouseout())

        After this code executes clicks on Trigger the handler will also append the message

        This event type can cause many headaches due to event bubbling For instance when themouse pointer moves out of the Inner element in this example a mouseout event will be sentto that then trickle up to Outer This can trigger the bound mouseout handler at inopportunet imes See the discussion for mouseleave() for a useful alternat ive

        Example 1 Show the number of t imes mouseout and mouseleave events are t riggeredmouseout f ires when the pointer moves out of the child element as well while mouseleave f iresonly when the pointer moves out of the bound element

        CSS

        divout width40height120pxmargin0 15pxbackground-colorD6EDFCfloatleftdivin width60height60background-colorFFCC00margin10px autop line-height1emmargin0padding0

        Javascript

        var i = 0 $(divoverout)mouseout(function() $(pfirstthis)text(mouse out) $(plastthis)text(++i) )mouseover(function() $(pfirstthis)text(mouse over) )

        var n = 0 $(diventerleave)bind(mouseenterfunction() $(pfirstthis)text(mouse enter) )bind(mouseleavefunction() $(pfirstthis)text(mouse leave) $(plastthis)text(++n) )

        HTML

        ltdiv class=out overoutgtltpgtmove your mouseltpgtltdiv class=in overoutgtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        ltdiv class=out enterleavegtltpgtmove your mouseltpgtltdiv class=in enterleavegtltpgtmove your mouseltpgtltpgt0ltpgtltdivgtltpgt0ltpgtltdivgt

        mouseover

        Bind an event handler to the mouseover JavaScript event or t rigger that event on anelement

        Added in version 10

        mouseover()jQuery

        This method is a shortcut for bind(mouseover handler) in the f irst two variat ions andtrigger(mouseover) in the third

        The mouseover event is sent to an element when the mouse pointer enters the element AnyHTML element can receive this event

        For example consider the HTML

        ltdiv id=outergt Outer ltdiv id=innergt Inner ltdivgtltdivgtltdiv id=othergt Trigger the handlerltdivgtltdiv id=loggtltdivgt

        The event handler can be boundto any element

        $(outer)mouseover(function() $(log)append(ltdivgtHandler for mouseover() calledltdivgt))

        Now when the mouse pointer moves over the Outer ltdivgt the message is appended to ltdivid=loggt We can also t rigger the event when another element is clicked

        $(other)cl ick(function() $(outer)mouseover())

        After this code executes clicks on Trigger the handler will also append the message

        This event type can cause many headaches due to event bubbling For instance when themouse pointer moves over the Inner element in this example a mouseover event will be sent tothat then trickle up to Outer This can trigger our bound mouseover handler at inopportunet imes See the discussion for mouseenter() for a useful alternat ive

        Example 1 Show the number of t imes mouseover and mouseenter events are t riggeredmouseover f ires when the pointer moves into the child element as well while mouseenter f iresonly when the pointer moves into the bound element

        CSS

        divout width40 height120px margin0 15px background-colorD6EDFC floatleft divin width60 height60 background-colorFFCC00 margin10px auto p l ine-height1em margin0 padding0

        Javascript

        var i = 0 $(divoverout)mouseover(function() i += 1 $(this)find(span)text( mouse over x + i ) )mouseout(function() $(this)find(span)text(mouse out ) )

        var n = 0 $(diventerleave)mouseenter(function() n += 1 $(this)find(span)text( mouse enter x + n ) )mouseleave(function() $(this)find(span)text(mouse leave) )

        HTML

        ltdiv class=out overoutgt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

        ltdiv class=out enterleavegt ltspangtmove your mouseltspangt ltdiv class=ingt ltdivgtltdivgt

        dblclick

        Bind an event handler to the dblclick JavaScript event or t rigger that event on an element

        Added in version 10

        dblclick()jQuery

        This method is a shortcut for bind(dblclick handler) in the f irst two variat ions andtrigger(dblclick) in the third The dblclick event is sent to an element when the element isdouble-clicked Any HTML element can receive this event For example consider the HTML

        ltdiv id=targetgt Double-click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be boundto any ltdivgt

        $(target)dblcl ick(function() alert(Handler for dblcl ick() called))

        Now double-clicking on this element displays the alert

        Handler for dblclick() called

        To trigger the event manually apply dblclick() without an argument

        $(other)cl ick(function() $(target)dblcl ick())

        After this code executes (single) clicks on Trigger the handler will also alert the message

        The dblclick event is only t riggered af ter this exact series of events

        The mouse button is depressed while the pointer is inside the element

        The mouse button is released while the pointer is inside the element

        The mouse button is depressed again while the pointer is inside the element within at ime window that is system-dependent

        The mouse button is released while the pointer is inside the element

        It is inadvisable to bind handlers to both the click and dblclick events for the same element Thesequence of events t riggered varies f rom browser to browser with some receiving two clickevents before the dblclick and others only one Double-click sensit ivity (maximum t ime betweenclicks that is detected as a double click) can vary by operat ing system and browser and is of tenuser-conf igurable

        Example 1 To bind a Hello World alert box the dblclick event on every paragraph on the page

        Javascript

        $(p)dblcl ick( function () alert(Hello World) )

        Example 2 Double click to toggle background color

        Javascript

        var divdbl = $(divfirst) divdbldblcl ick(function () divdbltoggleClass(dbl) )

        CSS

        div backgroundblue colorwhite height100px width150px divdbl backgroundyellowcolorblack

        HTML

        ltdivgtltdivgtltspangtDouble cl ick the blockltspangt

        click

        Bind an event handler to the click JavaScript event or t rigger that event on an element

        Added in version 10

        click()jQuery

        This method is a shortcut for bind(click handler) in the f irst two variat ions and t rigger(click)in the third

        The click event is sent to an element when the mouse pointer is over the element and themouse button is pressed and released Any HTML element can receive this event

        For example consider the HTMLltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be boundto any ltdivgt

        $(target)cl ick(function() alert(Handler for cl ick() called))

        Now if we click on this element the alert is displayed

        Handler for click() called

        We can also t rigger the event when a dif ferent element is clicked

        $(other)cl ick(function() $(target)cl ick())

        After this code executes clicks on Trigger the handler will also alert the message

        The click event is only t riggered af ter this exact series of events

        The mouse button is depressed while the pointer is inside the element

        The mouse button is released while the pointer is inside the element

        This is usually the desired sequence before taking an act ion If this is not required themousedown or mouseup event may be more suitable

        Example 1 To hide paragraphs on a page when they are clicked

        Javascript

        $(p)cl ick(function () $(this)sl ideUp() ) $(p)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

        CSS

        p colorred margin5px cursorpointer phil ite backgroundyellow

        HTML

        ltpgtFirst Paragraphltpgt

        ltpgtSecond Paragraphltpgt ltpgtYet one more Paragraphltpgt

        Example 2 To trigger the click event on all of the paragraphs on the page

        Javascript

        $(p)cl ick()

        mouseup

        Bind an event handler to the mouseup JavaScript event or t rigger that event on an element

        Added in version 10

        mouseup()jQuery

        This method is a shortcut for bind(mouseup handler) in the f irst variat ion andtrigger(mouseup) in the second

        The mouseup event is sent to an element when the mouse pointer is over the element and themouse button is released Any HTML element can receive this event

        For example consider the HTML

        ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be boundto any ltdivgt

        $(target)mouseup(function() alert(Handler for mouseup() called))

        Now if we click on this element the alert is displayed

        Handler for mouseup() called

        We can also t rigger the event when a dif ferent element is clicked

        $(other)cl ick(function() $(target)mouseup())

        After this code executes clicks on Trigger the handler will also alert the message

        If the user clicks outside an element drags onto it and releases the button this is st ill countedas a mouseup event This sequence of act ions is not t reated as a button press in most userinterfaces so it is usually better to use the click event unless we know that the mouseup eventis preferable for a part icular situat ion

        Example 1 Show texts when mouseup and mousedown event t riggering

        Javascript

        $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

        HTML

        ltpgtPress mouse and release hereltpgt

        mousedown

        Bind an event handler to the mousedown JavaScript event or t rigger that event on anelement

        Added in version 10

        mousedown()jQuery

        This method is a shortcut for bind(mousedown handler) in the f irst variat ion andtrigger(mousedown) in the second

        The mousedown event is sent to an element when the mouse pointer is over the element andthe mouse button is pressed Any HTML element can receive this event

        For example consider the HTML

        ltdiv id=targetgt Click hereltdivgtltdiv id=othergt Trigger the handlerltdivgt

        The event handler can be boundto any ltdivgt

        $(target)mousedown(function() alert(Handler for mousedown() called))

        Now if we click on this element the alert is displayed

        Handler for mousedown() called

        We can also t rigger the event when a dif ferent element is clicked

        $(other)cl ick(function() $(target)mousedown())

        After this code executes clicks on Trigger the handler will also alert the message

        The mousedown event is sent when any mouse button is clicked To act only on specif icbuttons we can use the event object s which property Not all browsers support this property(Internet Explorer uses button instead) but jQuery normalizes the property so that it is safe touse in any browser The value of which will be 1 for the lef t but ton 2 for the middle button or 3for the right button

        This event is primarily useful for ensuring that the primary button was used to begin a dragoperat ion if ignored strange results can occur when the user at tempts to use a context menuWhile the middle and right buttons can be detected with these propert ies this is not reliable InOpera 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 st ill countedas a mousedown event This sequence of act ions is t reated as a canceling of the buttonpress in most user interfaces so it is usually better to use the click event unless we know thatthe mousedown event is preferable for a part icular situat ion

        Example 1 Show texts when mouseup and mousedown event t riggering

        Javascript

        $(p)mouseup(function() $(this)append(ltspan style=colorF00gtMouse upltspangt) )mousedown(function() $(this)append(ltspan style=color00FgtMouse downltspangt) )

        HTML

        ltpgtPress mouse and release hereltpgt

        error

        Bind an event handler to the error JavaScript event

        Added in version 143

        error(eventData handler(eventObject))jQuery

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

        This method is a shortcut for bind(error handler)

        The error event is sent to elements such as images that are referenced by a document andloaded by the browser It is called if the element was not loaded correct ly

        For example consider a page with a simple image element

        ltimg alt=Book id=book gt

        The event handler can be bound to the image

        $(book) error(function() alert(Handler for error() called) ) attr(src missingpng)

        If the image cannot be loaded (for example because it is not present at the supplied URL) thealert is displayed

        Handler for error() called

        The event handler must be attached before the browser fires the error eventwhich is why the example sets the src attribute after attaching the handler Alsothe error event may not be correctly fired when the page is served locally errorrelies on HTTP status codes and will generally not be triggered if the URL usesthe file protocol

        Note A jQuery error event handler should not be at tached to the window object The browserf ires the windows error event when a script error occurs However the window error eventreceives dif ferent arguments and has dif ferent return value requirements than convent ionalevent handlers Use windowonerror instead

        Example 1 To hide the broken image icons for IE users you can try

        Javascript

        $(img) error(function() $(this)hide() ) attr(src missingpng)

        unload

        Bind an event handler to the unload JavaScript event

        Added in version 143

        unload(eventData handler(eventObject))jQuery

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

        This method is a shortcut for bind(unload handler)

        The unload event is sent to the window element when the user navigates away from the pageThis 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 t rigger the eventClosing the browser window will cause the event to be triggered Even a page reload will f irstcreate an unload event

        The exact handling of the unload event has varied from version to version ofbrowsers For example some versions of Firefox trigger the event when a link isfollowed but not when the window is closed In practical usage behavior shouldbe tested on all supported browsers and contrasted with the proprietarybeforeunload event

        Any unload event handler should be bound to the window object

        $(window)unload(function() alert(Handler for unload() called))

        After this code executes the alert will be displayed whenever the browser leaves the currentpage It is not possible to cancel the unload event with preventDefault () This event is availableso that scripts can perform cleanup when the user leaves the page

        Example 1 To display an alert when a page is unloaded

        Javascript

        $(window)unload( function () alert(Bye now) )

        load

        Bind an event handler to the load JavaScript event

        Added in version 143

        load(eventData handler(eventObject))jQuery

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute each t ime the event is t riggered

        This method is a shortcut for bind(load handler)

        The load 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 f ramesif rames and the window object

        For example consider a page with a simple image

        ltimg src=bookpng alt=Book id=book gt

        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 executedearlier it is usually best to place it in a handler sent to the ready() method

        The Ajax module also has a method named load() Which one is fired dependson the set of arguments passed

        Caveats of the load event when used with images

        A common challenge developers attempt to solve using the load() shortcut is toexecute a function when an image (or collection of images) have completelyloaded There are several known caveats with this that should be noted Theseare

        It doesnt work consistently nor reliably cross-browser

        It doesnt fire correctly in WebKit if the image src is set to the same src asbefore

        It doesnt correctly bubble up the DOM tree

        Can cease to fire for images that already live in the browsers cache

        Note The live() and delegate() methods cannot be used to detect the load eventof an iframe The load event does not correctly bubble up the parent documentand the eventtarget isnt set by Firefox IE9 or Chrome which is required to doevent delegation

        Note When calling load() using a URL without a suffixed selector expression the

        content is passed to html() prior to scripts being removed This executes the scriptblocks before they are discarded If load() is however called with a selectorexpression appended to the URL the scripts are stripped out prior to the DOMbeing updated which is why they are never executed An example of both casescan be seen below

        Here any JavaScript loaded into a as a part of the document will successfully execute

        $(a)load(articlehtml)

        However in this case script blocks in the document being loaded into b are stripped out priorto being executed

        $(b)load(articlehtml target)

        Example 1 Run a funct ion when the page is fully loaded including graphics

        Javascript

        $(window)load(function () run code)

        Example 2 Add the class bigImg to all images with height greater then 100 upon each imageload

        Javascript

        $( imguserIcon)load(function() if($(this)height() gt 100) $(this)addClass(bigImg) )

        ready

        Specify a funct ion to execute when the DOM is fully loaded

        Added in version 10

        ready(handler)jQuery

        handlerFunct ion A funct ion to execute af ter the DOM is ready

        While JavaScript provides the load event for execut ing code when a page is rendered thisevent does not get t riggered unt il all assets such as images have been completely received Inmost cases the script can be run as soon as the DOM hierarchy has been fully constructedThe handler passed to ready() is guaranteed to be executed af ter the DOM is ready so this isusually the best place to at tach all other event handlers and run other jQuery code When usingscripts that rely on the value of CSS style propert ies it s important to reference externalstylesheets or embed style elements before referencing the scripts

        In cases where code relies on loaded assets (for example if the dimensions of an image arerequired) the code should be placed in a handler for the load event instead

        The ready() method is generally incompatible with the ltbody onload=gtattribute If load must be used either do not use ready() or use jQuerys load()method to attach load event handlers to the window or to more specific items likeimages

        All three of the following syntaxes are equivalent

        $(document)ready(handler)

        $()ready(handler) (this is not recommended)

        $(handler)

        There is also $(document)bind(ready handler) This behaves similarly to the ready methodbut with one except ion If the ready event has already f ired and you try to bind(ready) thebound handler will not be executed Ready handlers bound this way are executed after anybound by the other three methods above

        The ready() method can only be called on a jQuery object matching the current document sothe selector can be omit ted

        The ready() method is typically used with an anonymous funct ion

        $(document)ready(function() Handler for ready() called)

        Which is equivalent to calling

        $(function() Handler for ready() called)

        If ready() is called af ter the DOM has been init ialized the new handler passed in will beexecuted immediately

        Aliasing the jQuery Namespace

        When using another JavaScript library we may wish to call $noConf lict () to avoid namespacedif f icult ies When this funct ion is called the $ shortcut is no longer available forcing us to writejQuery each t ime we would normally write $ However the handler passed to the ready()method can take an argument which is passed the global jQuery object This means we canrename the object within the context of our ready() handler without af fect ing other code

        jQuery(document)ready(function($) Code using $ as usual goes here)

        Example 1 Display a message when the DOM is loaded

        Javascript

        $(document)ready(function () $(p)text(The DOM is now loaded and can be manipulated))

        CSS

        p colorred

        HTML

        ltpgtNot loaded yetltpgt

        die

        Remove all event handlers previously at tached using live() f rom the elements

        Added in version 141

        die()jQuery

        Any handler that has been at tached with live() can be removed with die() This method isanalogous to calling unbind() with no arguments which is used to remove all handlers at tached

        with bind() See the discussions of live() and unbind() for further details

        Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

        die

        Remove an event handler previously at tached using live() f rom the elements

        Added in version 143

        die(eventTypes)jQuery

        eventTypesMap A map of one or more event types such as click or keydown and theircorresponding funct ions that are no longer to be executed

        Any handler that has been at tached with live() can be removed with die() This method isanalogous to unbind() which is used to remove handlers at tached with bind() See thediscussions of live() and unbind() for further details

        Note In order for die() to funct ion correct ly the selector used with it must match exact ly theselector init ially used with live()

        Example 1 Can bind and unbind events to the colored button

        Javascript

        function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () $(theone)l ive(click aClick) text(Can Click))$(unbind)cl ick(function () $(theone)die(click aClick) text(Does nothing))

        CSS

        button margin5px buttontheone colorred backgroundyellow

        HTML

        ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

        ltdiv style=displaynonegtClickltdivgt

        Example 2 To unbind all live events f rom all paragraphs write

        Javascript

        $(p)die()

        Example 3 To unbind all live click events f rom all paragraphs write

        Javascript

        $(p)die( cl ick )

        Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

        Javascript

        var foo = function () code to handle some kind of event

        $(p)l ive(click foo) now foo wil l be called when paragraphs are cl icked

        $(p)die(click foo) foo wil l no longer be called

        live

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

        Added in version 143

        live(events)jQuery

        eventsObject A map of one or more JavaScript event types and funct ions to executefor them

        This method is a variat ion on the basic bind() method for at taching event handlers to elementsWhen bind() is called the elements that the jQuery object refers to get the handler at tachedelements that get introduced later do not so they would require another bind() call Forinstance consider the HTML

        ltbodygt ltdiv class=clickmegt Click here ltdivgtltbodygt

        To bind a simple click handler to this element

        $(cl ickme)bind(cl ick function() Bound handler called)

        When the element is clicked the handler is called However suppose that af ter this anotherelement is added

        $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

        This new element also matches the selector clickme but since it was added af ter the call tobind() clicks on it will do nothing

        The live() method provides an alternat ive to this behavior To bind a click handler to the targetelement using this method

        $(cl ickme)l ive(cl ick function() Live handler called)

        And then later add a new element

        $(body)append(ltdiv class=clickmegtAnother targetltdivgt)

        Then clicks on the new element will also t rigger the handler

        To unbind the click handlers f rom all ltdiv class=clickmegt that were bound using live() use thedie() method

        $(cl ickme)die(click)

        Event Delegation

        The live() method is able to af fect elements that have not yet been added to the DOM throughthe use of event delegat ion a handler bound to an ancestor element is responsible for eventsthat are t riggered on its descendants The handler passed to live() is never bound to anelement instead live() binds a special handler to the root of the DOM tree In the exampleabove when the new element is clicked the following steps occur

        1 A click event is generated and passed to the ltdivgt for handling

        2 No handler is direct ly bound to the ltdivgt so the event bubbles up the DOM tree

        3 The event bubbles up unt il it reaches the root of the t ree which is where live() binds itsspecial handlers by default

        As of jQuery 14 event bubbling can optionally stop at a DOM element context

        4 The special click handler bound by live() executes

        5 This handler tests the target of the event object to see whether it should cont inue Thistest is performed by checking if $(eventtarget)closest(clickme) is able to locate amatching element

        6 If a matching element is found the original handler is called on it

        Because the test in step 5 is not performed unt il the event occurs elements can be added atany t ime and st ill respond to events

        See the discussion for bind() for more informat ion on event binding

        Multiple Events

        As of jQuery 141 live() can accept mult iple space-separated events similar to thefunct ionality provided in bind() For example you can live bind the mouseover and mouseoutevents at the same t ime like so

        $(hoverme)l ive(mouseover mouseout function(event) if ( eventtype == mouseover ) do something on mouseover else do something on mouseout )

        As of jQuery 143 you can bind mult iple live event handlers simultaneously by passing a map ofevent typehandler pairs

        $(a)l ive( cl ick function() do something on click mouseover function() do something on mouseover )

        Event Data

        As of jQuery 14 the opt ional eventData parameter is available for passing addit ionalinformat ion to the handler One handy use of this parameter is to work around issues causedby closures See the bind() methods Passing Event Data discussion for more informat ion

        Event Context

        As of jQuery 14 live events can be bound to a DOM element context rather than to thedefault document root To set this context use the jQuery() funct ions second argumentpassing in a single DOM element (as opposed to a jQuery collect ion or a selector)

        $(divcl ickme $(container)[0])l ive(click function() Live handler called)

        The live handler in this example is called only when ltdiv class=clickmegt is a descendant of anelement with an ID of container

        Caveats

        The live() technique is useful but due to its special approach cannot be simply subst ituted forbind() in all cases Specif ic dif ferences include

        DOM traversal methods are not supported for f inding elements to send to live()Rather the live() method should always be called direct ly af ter a selector as in theexample above

        To stop further handlers f rom execut ing af ter one bound using live() the handler mustreturn false Calling stopPropagat ion() will not accomplish this

        The paste and reset events in addit ion to change when used with inputs of type f ileare not fully supported by the live() method due to issues with simulat ing event bubblingin Internet Explorer In these cases the bind() method can be used instead

        In jQuery 13x only the following JavaScript events (in addit ion to custom events)could be bound with live() click dblclick keydown keypress keyup mousedown

        mousemove mouseout mouseover and mouseup

        As of jQuery 14 the live() method supports custom events as well as allJavaScript events that bubble

        As of jQuery 141 even focus and blur work with live (mapping to themore appropriate bubbling events focusin and focusout)

        As of jQuery 141 the hover event can be specified (mapping tomouseenter and mouseleave which in turn are mapped to mouseover andmouseout)

        Example 1 Click a paragraph to add another Note that live() binds the click event to allparagraphs - even new ones

        Javascript

        $(p)l ive(click function() $(this)after(ltpgtAnother paragraphltpgt))

        CSS

        p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

        HTML

        ltpgtClick meltpgt

        ltspangtltspangt

        Example 2 Cancel a default act ion and prevent it f rom bubbling up by returning false

        Javascript

        $(a)l ive(click function() return false )

        Example 3 Cancel only the default act ion by using the preventDefault method

        Javascript

        $(a)l ive(click function(event) eventpreventDefault())

        Example 4 Bind custom events with live()

        Javascript

        $(p)l ive(myCustomEvent function(e myName myValue) $(this)text(Hi there) $(span)stop()css(opacity 1) text(myName = + myName) fadeIn(30)fadeOut(1000))$(button)cl ick(function () $(p)trigger(myCustomEvent))

        CSS

        p colorred span colorblue

        HTML

        ltpgtHas an attached custom eventltpgt ltbuttongtTrigger custom eventltbuttongt ltspan style=displaynonegtltspangt

        Example 5 Use a map to bind mult iple live event handlers Note that live() binds the clickmouseover and mouseout events to all paragraphs acirceurordquo even new ones

        Javascript

        $(p)l ive( cl ick function() $(this)after(ltpgtAnother paragraphltpgt) mouseover function() $(this)addClass(over) mouseout function() $(this)removeClass(over) )

        CSS

        p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

        HTML

        ltpgtClick meltpgt ltspangtltspangt

        triggerHandler

        Execute all handlers at tached to an element for an event

        Added in version 12

        triggerHandler(eventType extraParameters)Object

        eventTypeString A string containing a JavaScript event type such as click orsubmit

        extraParametersArray An array of addit ional parameters to pass along to the eventhandler

        The t riggerHandler() method behaves similarly to t rigger() with the following except ions

        The t riggerHandler() method does not cause the default behavior of an event to occur(such as a form submission)

        While t rigger() will operate on all elements matched by the jQuery object t riggerHandler() only af fects the f irst matched element

        Events created with t riggerHandler() do not bubble up the DOM hierarchy if they arenot handled by the target element direct ly they do nothing

        Instead of returning the jQuery object (to allow chaining) t riggerHandler() returnswhatever value was returned by the last handler it caused to be executed If no handlersare t riggered it returns undef ined

        For more informat ion on this method see the discussion for t rigger()

        Example 1 If you called t riggerHandler() on a focus event - the browsers default focus act ionwould not be triggered only the event handlers bound to the focus event

        Javascript

        $(old)cl ick(function()$(input)trigger(focus))$(new)cl ick(function()$(input)triggerHandler(focus))$(input)focus(function()$(ltspangtFocusedltspangt)appendTo(body)fadeOut(1000))

        HTML

        ltbutton id=oldgttrigger(focus)ltbuttongtltbutton id=newgttriggerHandler(focus)ltbuttongtltbrgtltbrgt

        ltinput type=text value=To Be Focusedgt

        trigger

        Execute all handlers and behaviors at tached to the matched elements for the given event type

        Added in version 13

        trigger(event)jQuery

        eventEvent A jQueryEvent object

        Any event handlers at tached with bind() or one of its shortcut methods are t riggered when thecorresponding event occurs They can be f ired manually however with the t rigger() method Acall to t rigger() executes the handlers in the same order they would be if the event weretriggered naturally by the user

        $(foo)bind(cl ick function() alert($(this)text()) ) $(foo)trigger(cl ick)

        As of jQuery 13 t rigger()ed events bubble up the DOM tree an event handler can stop thebubbling by returning false f rom the handler or calling the stopPropagat ion() method on theevent object passed into the event Although t rigger() simulates an event act ivat ion completewith a synthesized event object it does not perfect ly replicate a naturally-occurring event

        To trigger handlers bound via jQuery without also t riggering the nat ive event use

        t riggerHandler() instead

        When we def ine a custom event type using the bind() method the second argument tot rigger() can become useful For example suppose we have bound a handler for the customevent to our element instead of the built -in click 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 f irst parameter to an event handler but if addit ionalparameters are specif ied during a t rigger() call these parameters will be passed along to thehandler as well To pass more than one parameter use an array as shown here As of jQuery162 a single parameter can be passed without using an array

        Note the dif ference between the extra parameters were passing here and the eventDataparameter to the bind() method Both are mechanisms for passing informat ion to an eventhandler but the extraParameters argument to t rigger() allows informat ion to be determined atthe t ime the event is t riggered while the eventData argument to bind() requires the informat ionto be already computed at the t ime the handler is bound

        Example 1 Clicks to button 2 also t rigger a click for button 1

        Javascript

        $(buttonfirst)cl ick(function () update($(spanfirst)))$(buttonlast)cl ick(function () $(buttonfirst)trigger(cl ick)

        update($(spanlast)))

        function update(j) var n = parseInt(jtext() 10)j text(n + 1)

        CSS

        button margin10px div colorblue font-weightbold span colorred

        HTML

        ltbuttongtButton 1ltbuttongtltbuttongtButton 2ltbuttongtltdivgtltspangt0ltspangt button 1 clicksltdivgt

        ltdivgtltspangt0ltspangt button 2 clicksltdivgt

        Example 2 To submit the f irst form without using the submit() funct ion t ry

        Javascript

        $(formfirst)trigger(submit)

        Example 3 To submit the f irst form without using the submit() funct ion t ry

        Javascript

        var event = jQueryEvent(submit)$(formfirst)trigger(event)if ( eventisDefaultPrevented() ) Perform an action

        Example 4 To pass arbit rary data to an event

        Javascript

        $(p)cl ick( function (event a b) when a normal cl ick fires a and b are undefined for a trigger l ike below a refers to foo and b refers to bar

        )trigger(click [foo bar])

        Example 5 To pass arbit rary data through an event object

        Javascript

        var event = jQueryEvent(logged)eventuser = fooeventpass = bar$(body)trigger(event)

        Example 6 Alternat ive way to pass data through an event object

        Javascript

        $(body)trigger(typeloggeduserfoopassbar

        )

        one

        Attach a handler to an event for the elements The handler is executed at most once perelement

        Added in version 11

        one(eventType eventData handler(eventObject))jQuery

        eventTypeString A string containing one or more JavaScript event typessuch as click or submit or custom event names

        eventDataObject (opt ional) A map of data that will be passed to theevent handler

        handler(eventObject)Funct ion A funct ion to execute at the t ime the event is t riggered

        This method is ident ical to bind() except that the handler is unbound af ter its f irst invocat ionFor example

        $(foo)one(click function() alert(This wil l be displayed only once))

        After the code is executed a click on the element with ID foo will display the alert Subsequentclicks will do nothing This code is equivalent to

        $(foo)bind(click function( event ) alert(This wil l be displayed only once) $(this)unbind( event ))

        In other words explicit ly calling unbind() f rom within a regularly-bound handler has exact ly thesame effect

        If the f irst argument contains more than one space-separated event types the event handler is

        called once for each event type

        Example 1 Tie a one-t ime click to each div

        Javascript

        var n = 0$(div)one(click function() var index = $(div)index(this) $(this)css( borderStyleinset cursorauto ) $(p)text(Div at index + index + cl icked + Thats + ++n + total cl icks))

        CSS

        div width60px height60px margin5px floatleftbackgroundgreen border10px outset cursorpointer p colorred margin0 clearleft

        HTML

        ltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

        ltpgtClick a green squareltpgt

        Example 2 To display the text of all paragraphs in an alert box the f irst t ime each of them isclicked

        Javascript

        $(p)one(click function()alert( $(this)text() ))

        unbind

        Remove a previously-at tached event handler f rom the elements

        Added in version 10

        unbind(event)jQuery

        eventObject A JavaScript event object as passed to an event handler

        Any handler that has been at tached with bind() can be removed with unbind() In the simplestcase with no arguments unbind() removes all handlers at tached to the elements

        $(foo)unbind()

        This version removes the handlers regardless of type To be more precise we can pass anevent type

        $(foo)unbind(cl ick)

        By specifying the click event type only handlers for that event type will be unbound Thisapproach can st ill have negat ive ramif icat ions if other scripts might be at taching behaviors tothe same element however Robust and extensible applicat ions typically demand the two-argument version for this reason

        var handler = function() alert(The quick brown fox jumps over the lazy dog)$(foo)bind(cl ick handler)$(foo)unbind(cl ick handler)

        By naming the handler we can be assured that no other funct ions are caught in the crossf ireNote that the following will not work

        $(foo)bind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

        wil l NOT work$(foo)unbind(cl ick function() alert(The quick brown fox jumps over the lazy dog))

        Even though the two funct ions are ident ical in content they are created separately and soJavaScript is f ree to keep them as dist inct funct ion objects To unbind a part icular handler weneed a reference to that funct ion and not a dif ferent one that happens to do the same thing

        Note Because the live() method binds event handlers to document by defaultcalling unbind() on document will unbind the handlers bound by live() as wellFor example $(document)unbind(click) will remove not only$(document)bind(click fn1)

        but also

        $(afoo)live(click fn2)

        Note Using a proxied function to unbind an event on an element will unbind allproxied functions on that element as the same proxy function is used for allproxied events To allow unbinding a specific event use unique class names onthe event (eg clickproxy1 clickproxy2) when attaching them

        Using Namespaces

        Instead of maintaining references to handlers in order to unbind them we can namespace theevents and use this capability to narrow the scope of our unbinding act ions As shown in thediscussion for the bind() method namespaces are def ined by using a period () character whenbinding a handler

        $(foo)bind(cl ickmyEvents handler)

        When a handler is bound in this fashion we can st ill unbind it the normal way

        $(foo)unbind(cl ick)

        However if we want to avoid af fect ing other handlers we can be more specif ic

        $(foo)unbind(cl ickmyEvents)

        We can also unbind all of the handlers in a namespace regardless of event type

        $(foo)unbind(myEvents)

        It is part icularly useful to at tach namespaces to event bindings when we are developing plug-insor otherwise writ ing code that may interact with other event-handling code in the future

        Using the Event Object

        The third form of the unbind() method is used when we wish to unbind a handler f rom withinitself For example suppose we wish to t rigger an event handler only three t imes

        var timesClicked = 0$(foo)bind(cl ick function(event) alert(The quick brown fox jumps over the lazy dog) timesClicked++ if (timesClicked gt= 3) $(this)unbind(event) )

        The handler in this case must take a parameter so that we can capture the event object anduse it to unbind the handler af ter the third click The event object contains the contextnecessary for unbind() to know which handler to remove This example is also an illustrat ion ofa closure Since the handler refers to the t imesClicked variable which is def ined outside thefunct ion increment ing the variable has an ef fect even between invocat ions of the handler

        Example 1 Can bind and unbind events to the colored button

        Javascript

        function aClick() $(div)show()fadeOut(slow)$(bind)cl ick(function () could use bind(cl ick aClick) instead but for variety$(theone)cl ick(aClick) text(Can Click))$(unbind)cl ick(function () $(theone)unbind(cl ick aClick) text(Does nothing))

        CSS

        button margin5px buttontheone colorred backgroundyellow

        HTML

        ltbutton id=theonegtDoes nothingltbuttongtltbutton id=bindgtBind Clickltbuttongtltbutton id=unbindgtUnbind Clickltbuttongt

        ltdiv style=displaynonegtClickltdivgt

        Example 2 To unbind all events f rom all paragraphs write

        Javascript

        $(p)unbind()

        Example 3 To unbind all click events f rom all paragraphs write

        Javascript

        $(p)unbind( cl ick )

        Example 4 To unbind just one previously bound handler pass the funct ion in as the secondargument

        Javascript

        var foo = function () code to handle some kind of event

        $(p)bind(click foo) now foo wil l be called when paragraphs are cl icked

        $(p)unbind(click foo) foo wil l no longer be called

        bind

        Attach a handler to an event for the elements

        Added in version 14

        bind(events)jQuery

        eventsObject A map of one or more JavaScript event types and funct ions to executefor them

        The bind() method is the primary means of at taching behavior to a document All JavaScriptevent types such as focus mouseover and resize are allowed for eventType The error eventon the window object uses nonstandard convent ions and is not supported by jQuery at tach ahandler direct ly to the window object instead The beforeunload event is supported cross-browser in jQuery 151 and 16+ but is not supported in IE for jQuery 152 due to a regression

        The jQuery library provides shortcut methods for binding the standard event types such asclick() for bind(click) A descript ion of each can be found in the discussion of its shortcutmethod blur focus focusin focusout load resize scroll unload click dblclick mousedownmouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error

        Any string is legal for eventType if the string is not the name of a nat ive JavaScript event thenthe handler is bound to a custom event These events are never called by the browser but maybe triggered manually f rom other JavaScript code using t rigger() or t riggerHandler()

        If the eventType string contains a period () character then the event is namespaced Theperiod character separates the event f rom its namespace For example in the callbind(clickname handler) the string click is the event type and the string name is thenamespace Namespacing allows us to unbind or t rigger some events of a type withoutaf fect ing others See the discussion of unbind() for more informat ion

        When an event reaches an element all handlers bound to that event type for the element aref ired If there are mult iple handlers registered they will always execute in the order in which theywere bound After all handlers have executed the event cont inues along the normal eventpropagat ion path

        A basic usage of bind() is

        $(foo)bind(cl ick function() alert(User cl icked on foo))

        This code will cause the element with an ID of foo to respond to the click event When a userclicks inside this element thereafter the alert will be shown

        Multiple Events

        Mult iple event types can be bound at once by including each one separated by a space

        $(foo)bind(mouseenter mouseleave function() $(this)toggleClass(entered))

        The ef fect of this on ltdiv id=foogt (when it does not init ially have the entered class) is toadd the entered class when the mouse enters the ltdivgt and remove the class when themouse leaves

        As of jQuery 14 we can bind mult iple event handlers simultaneously by passing a map of eventtypehandler pairs

        $(foo)bind( cl ick function() do something on click mouseenter function() do something on mouseenter )

        Event Handlers

        The handler parameter takes a callback funct ion as shown above Within the handler thekeyword this refers to the DOM element to which the handler is bound To make use of theelement in jQuery it can be passed to the normal $() funct ion For example

        $(foo)bind(cl ick function() alert($(this)text()))

        After this code is executed when the user clicks inside the element with an ID of foo its textcontents will be shown as an alert

        As of jQuery 142 duplicate event handlers can be bound to an element instead of beingdiscarded For example

        function test() alert(Hello) $(button)cl ick( test )$(button)cl ick( test )

        The above will generate two alerts when the button is clicked

        In jQuery 143 you can now pass in false in place of an event handler This will bind an eventhandler that s equivalent to funct ion() return false This funct ion can be removed at a latert ime by calling unbind( eventName false )

        The Event object

        The handler callback funct ion can also take parameters When the funct ion is called theJavaScript event object will be passed to the f irst parameter

        The event object is of ten unnecessary and the parameter omit ted as suff icient context isusually available when the handler is bound to know exact ly what needs to be done when thehandler is t riggered However at t imes it becomes necessary to gather more informat ion aboutthe users environment at the t ime the event was init iated View the full Event Object

        Returning false f rom a handler is equivalent to calling both preventDefault () andstopPropagat ion() on the event object

        Using the event object in a handler looks like this

        $(document)ready(function() $(foo)bind(cl ick function(event) alert(The mouse cursor is at ( + eventpageX + + eventpageY + )) ))

        Note the parameter added to the anonymous funct ion This code will cause a click on theelement with ID foo to report the page coordinates of the mouse cursor at the t ime of the click

        Passing Event Data

        The opt ional eventData parameter is not commonly used When provided this argument allowsus to pass addit ional informat ion to the handler One handy use of this parameter is to workaround issues caused by closures For example suppose we have two event handlers that bothrefer to the same external variable

        var message = Spoon$(foo)bind(cl ick function() alert(message))message = Not in the face$(bar)bind(cl ick function() alert(message))

        Because the handlers are closures that both have message in their environment both willdisplay the message Not in the face when triggered The variables value has changed Tosidestep this we can pass the message in using eventData

        var message = Spoon$(foo)bind(cl ick msg message function(event) alert(eventdatamsg))message = Not in the face$(bar)bind(cl ick msg message function(event) alert(eventdatamsg))

        This t ime the variable is not referred to direct ly within the handlers instead the variable is

        passed in by value through eventData which f ixes the value at the t ime the event is boundThe f irst handler will now display Spoon while the second will alert Not in the face

        Note that objects are passed to functions by reference which further complicatesthis scenario

        If eventData is present it is the second argument to the bind() method if no addit ional dataneeds to be sent to the handler then the callback is passed as the second and f inal argument

        See the trigger() method reference for a way to pass data to a handler at the timethe event happens rather than when the handler is bound

        As of jQuery 14 we can no longer at tach data (and thus events) to object embed or appletelements because crit ical errors occur when at taching data to Java applets

        Note Although demonstrated in the next example it is inadvisable to bind handlers to both theclick and dblclick events for the same element The sequence of events t riggered varies f rombrowser to browser with some receiving two click events before the dblclick and others onlyone Double-click sensit ivity (maximum t ime between clicks that is detected as a double click)can vary by operat ing system and browser and is of ten user-conf igurable

        Example 1 Handle click and double-click for the paragraph Note the coordinates are windowrelat ive so in this case relat ive to the demo if rame

        Javascript

        $(p)bind(click function(event)var str = ( + eventpageX + + eventpageY + )$(span)text(Click happened + str))$(p)bind(dblcl ick function()$(span)text(Double-click happened in + thisnodeName))$(p)bind(mouseenter mouseleave function(event)$(this)toggleClass(over))

        CSS

        p backgroundyellow font-weightbold cursorpointer padding5px pover background ccc span colorred

        HTML

        ltpgtClick or double cl ick hereltpgtltspangtltspangt

        Example 2 To display each paragraphs text in an alert box whenever it is clicked

        Javascript

        $(p)bind(click function()alert( $(this)text() ))

        Example 3 You can pass some extra data before the event handler

        Javascript

        function handler(event) alert(eventdatafoo)$(p)bind(click foo bar handler)

        Example 4 Cancel a default act ion and prevent it f rom bubbling up by returning false

        Javascript

        $(form)bind(submit function() return false )

        Example 5 Cancel only the default act ion by using the preventDefault () method

        Javascript

        $(form)bind(submit function(event) eventpreventDefault())

        Example 6 Stop an event f rom bubbling without prevent ing the default act ion by using thestopPropagat ion() method

        Javascript

        $(form)bind(submit function(event) eventstopPropagation())

        Example 7 Bind custom events

        Javascript

        $(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)cl ick(function () $(p)trigger(myCustomEvent [ John ]))

        CSS

        p colorred span colorblue

        HTML

        ltpgtHas an attached custom eventltpgtltbuttongtTrigger custom eventltbuttongtltspan style=displaynonegtltspangt

        Example 8 Bind mult iple events simultaneously

        Javascript

        $(divtest)bind( cl ick function() $(this)addClass(active) mouseenter function() $(this)addClass(inside) mouseleave function() $(this)removeClass(inside) )

        Deferred Object

        deferredpipe

        Utility method to f ilter andor chain Deferreds

        Added in version 16

        deferredpipe(doneFilter failFilter)Promise

        doneFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isresolved

        failFilterFunct ion (opt ional) An opt ional funct ion that is called when the Deferred isrejected

        The deferredpipe() method returns a new promise that f ilters the status and values of adeferred through a funct ion The doneFilter and failFilter funct ions f ilter the original deferredsresolved rejected status and values These f ilter funct ions can return a new value to bepassed along to the piped promises done() or fail() callbacks or they can return anotherobservable object (Deferred Promise etc) which will pass its resolved rejected status andvalues to the piped promises callbacks If the f ilter funct ion used is null or not specif ied thepiped promise will be resolved or rejected with the same values as the original

        Example 1 Filter resolve value

        Javascript

        var defer = $Deferred() fi ltered = deferpipe(function( value ) return value 2 )

        deferresolve( 5 )fi ltereddone(function( value ) alert( Value is ( 25 = ) 10 + value ))

        Example 2 Filter reject value

        Javascript

        var defer = $Deferred() fi ltered = deferpipe( null function( value ) return value 3 )

        deferreject( 6 )fi lteredfail(function( value ) alert( Value is ( 36 = ) 18 + value ))

        Example 3 Chain tasks

        Javascript

        var request = $ajax( url dataType json ) chained = requestpipe(function( data ) return $ajax( url2 data user datauserId ) )

        chaineddone(function( data ) data retrieved from url2 as provided by the first request)

        deferredalways

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

        Added in version 16

        deferredalways(alwaysCallbacks)Deferred

        alwaysCallbacksFunct ion A funct ion or array of funct ions that is called when theDeferred is resolved or rejected

        The argument can be either a single funct ion or an array of funct ions When the Deferred isresolved or rejected the alwaysCallbacks are called Since deferredalways() returns theDeferred object other methods of the Deferred object can be chained to this one includingaddit ional always() methods When the Deferred is resolved or rejected callbacks are executedin the order they were added using the arguments provided to the resolve reject resolveWithor rejectWith method calls For more informat ion see the documentat ion for Deferred object

        Example 1 Since the jQueryget() method returns a jqXHR object which is derived from aDeferred object we can at tach a callback for both success and error using thedeferredalways() method

        Javascript

        $get(testphp)always( function() alert($get completed with success or error callback arguments) )

        promise

        Return a Promise object to observe when all act ions of a certain type bound to the collect ionqueued or not have f inished

        Added in version 16

        promise(type target)Promise

        typeString (opt ional) The type of queue that needs to be observed

        targetObject (opt ional) Object onto which the promise methods have to be at tached

        The promise() method returns a dynamically generated Promise that is resolved once allact ions of a certain type bound to the collect ion queued or not have ended

        By default type is fx which means the returned Promise is resolved when all animat ions ofthe selected elements have completed

        Resolve context and sole argument is the collect ion onto which promise() has been called

        If target is provided promise() will at tach the methods onto it and then return this object ratherthan create a new one This can be useful to at tach the Promise behavior to an object thatalready exists

        Note The returned Promise is linked to a Deferred object stored on the data() foran element Since the remove() method removes the elements data as well asthe element itself it will prevent any of the elements unresolved Promises fromresolving If it is necessary to remove an element from the DOM before its Promiseis resolved use detach() instead and follow with removeData() after resolution

        Example 1 Using promise() on a collect ion with no act ive animat ion returns a resolved Promise

        Javascript

        var div = $( ltdiv gt )

        divpromise()done(function( arg1 ) wil l fire right away and alert true alert( this === div ampamp arg1 === div ))

        Example 2 Resolve the returned Promise when all animat ions have ended (including thoseinit iated in the animat ion callback or added later on)

        CSS

        div height 50px width 50px float left margin-right 10px display none background-color 090

        HTML

        ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

        Javascript

        $(button)bind( cl ick function() $(p)append( Started) $(div)each(function( i ) $( this )fadeIn()fadeOut( 1000 (i+1) ) )

        $( div )promise()done(function() $( p )append( Finished ) ))

        Example 3 Resolve the returned Promise using a $when() statement (the promise() methodmakes it possible to do this with jQuery collect ions)

        CSS

        div height 50px width 50px float left margin-right 10px display none background-color 090

        HTML

        ltbuttongtGoltbuttongtltpgtReadyltpgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

        Javascript

        var effect = function() return $(div)fadeIn(800)delay(1200)fadeOut()

        $(button)bind( cl ick function() $(p)append( Started )

        $when( effect() )done(function() $(p)append( Finished ) ))

        deferredpromise

        Return a Deferreds Promise object

        Added in version 15

        deferredpromise(target)Promise

        targetObject (opt ional) Object onto which the promise methods have to be at tached

        The deferredpromise() method allows an asynchronous funct ion to prevent other code frominterfering with the progress or status of its internal request The Promise exposes only theDeferred methods needed to at tach addit ional handlers or determine the state (then done failisResolved and isRejected) but not ones that change the state (resolve reject resolveWithand rejectWith) As of jQuery 16 the Promise also exposes the always and pipe Deferredmethods

        If target is provided deferredpromise() will at tach the methods onto it and then return thisobject rather than create a new one This can be useful to at tach the Promise behavior to anobject that already exists

        If you are creat ing a Deferred keep a reference to the Deferred so that it can be resolved orrejected at some point Return only the Promise object via deferredpromise() so other codecan register callbacks or inspect the current state

        For more informat ion see the documentat ion for Deferred object

        Example 1 Create a Deferred and set two t imer-based funct ions to either resolve or reject theDeferred af ter a random interval Whichever one f ires f irst wins and will call one of thecallbacks The second t imeout has no ef fect since the Deferred is already complete (in aresolved or rejected state) f rom the f irst t imeout act ion

        Javascript

        Create a Deferred and return its Promisefunction asyncEvent() var dfd = new jQueryDeferred() setTimeout(function() dfdresolve(hurray) Mathfloor(Mathrandom()1500)) setTimeout(function() dfdreject(sorry) Mathfloor(Mathrandom()1500)) return dfdpromise()

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

        Example 2 Use the target argument to promote an exist ing object to a Promise

        Javascript

        Existing objectvar obj = hello function( name ) alert( Hello + name ) Create a Deferreddefer = $Deferred()

        Set object as a promisedeferpromise( obj )

        Resolve the deferreddeferresolve( John )

        Use the object as a Promiseobjdone(function( name ) objhello( name ) wil l alert Hello John)hello( Karl ) wil l alert Hello Karl

        jQuerywhen see Core

        deferredresolveWith

        Resolve a Deferred object and call any doneCallbacks with the given context and args

        Added in version 15

        deferredresolveWith(context args)Deferred

        context Object Context passed to the doneCallbacks as the this object

        argsArray (opt ional) An opt ional array of arguments that are passed to thedoneCallbacks

        Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

        When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

        deferredrejectWith

        Reject a Deferred object and call any failCallbacks with the given context and args

        Added in version 15

        deferredrejectWith(context args)Deferred

        context Object Context passed to the failCallbacks as the this object

        argsArray (opt ional) An opt ional array of arguments that are passed to thefailCallbacks

        Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

        When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

        deferredfail

        Add handlers to be called when the Deferred object is rejected

        Added in version 15

        deferredfail(failCallbacks failCallbacks)Deferred

        failCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is rejected

        failCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is rejected

        The deferredfail() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is rejected the failCallbacks are calledCallbacks are executed in the order they were added Since deferredfail() returns the deferredobject other methods of the deferred object can be chained to this one including addit ionaldeferredfail() methods The failCallbacks are executed using the arguments provided to thedeferredreject() or deferredrejectWith() method call in the order they were added For moreinformat ion see the documentat ion for Deferred object

        Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred you can at tach a success and failure callback using the deferreddone() anddeferredfail() methods

        Javascript

        $get(testphp) done(function() alert($get succeeded) ) fai l(function() alert($get fai led) )

        deferreddone

        Add handlers to be called when the Deferred object is resolved

        Added in version 15

        deferreddone(doneCallbacks doneCallbacks)Deferred

        doneCallbacksFunct ion A funct ion or array of funct ions that are called when theDeferred is resolved

        doneCallbacksFunct ion (opt ional) Opt ional addit ional funct ions or arrays of funct ionsthat are called when the Deferred is resolved

        The deferreddone() method accepts one or more arguments all of which can be either a singlefunct ion or an array of funct ions When the Deferred is resolved the doneCallbacks are calledCallbacks are executed in the order they were added Since deferreddone() returns thedeferred object other methods of the deferred object can be chained to this one includingaddit ional done() methods When the Deferred is resolved doneCallbacks are executed usingthe arguments provided to the resolve or resolveWith method call in the order they were addedFor more informat ion see the documentat ion for Deferred object

        Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach a success callback using the done() method

        Javascript

        $get(testphp)done(function() alert($get succeeded) )

        Example 2 Resolve a Deferred object when the user clicks a button t riggering a number ofcallback funct ions

        Javascript

        3 functions to call when the Deferred object is resolvedfunction fn1() $(p)append( 1 )function fn2() $(p)append( 2 )function fn3(n) $(p)append(n + 3 + n)

        create a deferred objectvar dfd = $Deferred()

        add handlers to be called when dfd is resolveddfd done() can take any number of functions or arrays of functionsdone( [fn1 fn2] fn3 [fn2 fn1] ) we can chain done methods toodone(function(n) $(p)append(n + were done))

        resolve the Deferred object when the button is cl icked$(button)bind(click function() dfdresolve(and))

        HTML

        ltbuttongtGoltbuttongt ltpgtReadyltpgt

        deferredthen

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

        Added in version 15

        deferredthen(doneCallbacks failCallbacks)Deferred

        doneCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isresolved

        failCallbacksFunct ion A funct ion or array of funct ions called when the Deferred isrejected

        Both arguments can be either a single funct ion or an array of funct ions Either argument can

        also be null if no callback of that type is desired Alternat ively use done() or fail() to set onlydoneCallbacks or failCallbacks When the Deferred is resolved the doneCallbacks are called Ifthe Deferred is instead rejected the failCallbacks are called Callbacks are executed in the orderthey were added Since deferredthen returns the deferred object other methods of thedeferred object can be chained to this one including addit ional then() methods For moreinformat ion see the documentat ion for Deferred object

        Example 1 Since the jQueryget method returns a jqXHR object which is derived from aDeferred object we can at tach handlers using the then method

        Javascript

        $get(testphp)then( function() alert($get succeeded) function() alert($get fai led) )

        deferredreject

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

        Added in version 15

        deferredreject(args)Deferred

        argsObject Opt ional arguments that are passed to the failCallbacks

        Normally only the creator of a Deferred should call this method you can prevent other codefrom changing the Deferreds state by returning a restricted Promise object throughdeferredpromise()

        When the Deferred is rejected any failCallbacks added by deferredthen or deferredfail arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the deferredreject() call Any failCallbacks added af ter the Deferred enters the rejectedstate are executed immediately when they are added using the arguments that were passed tothe reject() call For more informat ion see the documentat ion for Deferred object

        deferredisRejected

        Determine whether a Deferred object has been rejected

        Added in version 15

        deferredisRejected()Boolean

        Returns t rue if the Deferred object is in the rejected state meaning that either deferredreject()

        or deferredrejectWith() has been called for the object and the failCallbacks have been called (orare in the process of being called)

        Note that a Deferred object can be in one of three states unresolved resolved or rejecteduse deferredisResolved() to determine whether the Deferred object is in the resolved stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

        deferredisResolved

        Determine whether a Deferred object has been resolved

        Added in version 15

        deferredisResolved()Boolean

        Returns t rue if the Deferred object is in the resolved state meaning that eitherdeferredresolve() or deferredresolveWith() has been called for the object and thedoneCallbacks 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 rejecteduse deferredisRejected() to determine whether the Deferred object is in the rejected stateThese methods are primarily useful for debugging for example to determine whether aDeferred has already been resolved even though you are inside code that intended to reject it

        deferredresolve

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

        Added in version 15

        deferredresolve(args)Deferred

        argsObject Opt ional arguments that are passed to the doneCallbacks

        When the Deferred is resolved any doneCallbacks added by deferredthen or deferreddone arecalled Callbacks are executed in the order they were added Each callback is passed the argsfrom the resolve() Any doneCallbacks added af ter the Deferred enters the resolved state areexecuted immediately when they are added using the arguments that were passed to theresolve() call For more informat ion see the documentat ion for Deferred object

        Effects

        fadeToggle

        Display or hide the matched elements by animat ing their opacity

        Added in version 144

        fadeToggle(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackFunct ion (opt ional) A funct ion to call once the animat ion is complete

        The fadeToggle() method animates the opacity of the matched elements When called on avisible element the element s display style property is set to none once the opacity reaches 0so the element no longer af fects the layout of the page

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        Easing

        The string represent ing an easing funct ion specif ies the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easing implementat ions in thejQuery library are the default called swing and one that progresses at a constant pace calledlinear More easing funct ions are available with the use of plug-ins most notably the jQuery UIsuite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

        As of jQuery 16 the promise() method can be used in conjunct ion with the deferreddone()method to execute a single callback for the animat ion as a whole when all matching elementshave completed their animat ions ( See the example for promise() )

        Example 1 Fades f irst paragraph in or out complet ing the animat ion within 600 millisecondsand using a linear easing Fades last paragraph in or out for 200 milliseconds insert ing af inished message upon complet ion

        Javascript

        $(buttonfirst)cl ick(function() $(pfirst)fadeToggle(slow l inear))$(buttonlast)cl ick(function () $(plast)fadeToggle(fast function () $(log)append(ltdivgtfinishedltdivgt) ))

        HTML

        ltbuttongtfadeToggle p1ltbuttongtltbuttongtfadeToggle p2ltbuttongtltpgtThis paragraph has a slow l inear fadeltpgt

        ltpgtThis paragraph has a fast animationltpgtltdiv id=loggtltdivgt

        jQueryfxinterval

        The rate (in milliseconds) at which animat ions f ire

        Added in version 143

        This property can be manipulated to adjust the number of f rames per second at whichanimat ions will run The default is 13 milliseconds Making this a lower number could make theanimat ions run smoother in faster browsers (such as Chrome) but there may be performanceand CPU implicat ions of doing so

        Since jQuery uses one global interval no animat ion should be running or all animat ions shouldstop for the change of this property to take ef fect

        NotejQueryfxinterval current ly has no ef fect in browsers that support therequestAnimat ionFrame property such as Google Chrome 11 This behavior is subject tochange in a future release

        Example 1 Cause all animat ions to run with less f rames

        Javascript

        jQueryfxinterval = 100

        $(input)cl ick(function() $(div)toggle( 3000 ))

        CSS

        div width50px height30px margin5px floatleft backgroundgreen

        HTML

        ltpgtltinput type=button value=Rungtltpgtltdivgtltdivgt

        delay

        Set a t imer to delay execut ion of subsequent items in the queue

        Added in version 14

        delay(durat ion queueName)jQuery

        durat ionInteger An integer indicat ing the number of milliseconds to delay execut ionof the next item in the queue

        queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue

        Added to jQuery in version 14 the delay() method allows us to delay the execut ion offunct ions that follow it in the queue It can be used with the standard ef fects queue or with acustom queue Only subsequent events in a queue are delayed for example this will not delaythe no-arguments forms of show() or hide() which do not use the ef fects queue

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        Using the standard ef fects queue we can for example set an 800-millisecond delay betweenthe slideUp() and fadeIn() of ltdiv id=foogt

        $(foo)sl ideUp(300)delay(800)fadeIn(400)

        When this statement is executed the element slides up for 300 milliseconds and then pausesfor 800 milliseconds before fading in for 400 milliseconds

        The delay() method is best for delaying between queued jQuery effects Because

        it is limitedacirceurordquoit doesnt for example offer a way to cancel the delayacirceurordquodelay() isnot a replacement for JavaScripts native setTimeout function which may be moreappropriate for certain use cases

        Example 1 Animate the hiding and showing of two divs delaying the f irst before showing it

        CSS

        div position absolute width 60px height 60px float left first background-color 3f3 left 0second background-color 33f left 80px

        Javascript

        $(button)cl ick(function() $(divfirst)sl ideUp(300)delay(800)fadeIn(400) $(divsecond)sl ideUp(300)fadeIn(400) )

        HTML

        ltpgtltbuttongtRunltbuttongtltpgtltdiv class=firstgtltdivgtltdiv class=secondgtltdivgt

        jQueryfxoff

        Globally disable all animat ions

        Added in version 13

        When this property is set to t rue all animat ion methods will immediately set elements to theirf inal state when called rather than displaying an ef fect This may be desirable for a couplereasons

        jQuery is being used on a low-resource device

        Users are encountering accessibility problems with the animat ions (see the art icle TurnOff Animat ion for more informat ion)

        Animat ions can be turned back on by sett ing the property to false

        Example 1 Toggle animat ion on and of f

        Javascript

        var toggleFx = function() $fxoff = $fxofftoggleFx()

        $(button)cl ick(toggleFx)

        $(input)cl ick(function() $(div)toggle(slow))

        CSS

        div width50px height30px margin5px floatleft backgroundgreen

        HTML

        ltpgtltinput type=button value=Rungt ltbuttongtToggle fxltbuttongtltpgtltdivgtltdivgt

        clearQueue see Data

        dequeue see Data

        queue see Data

        queue see Data

        stop

        Stop the current ly-running animat ion on the matched elements

        Added in version 12

        stop(clearQueue jumpToEnd)jQuery

        clearQueueBoolean (opt ional) A Boolean indicat ing whether to remove queuedanimat ion as well Defaults to false

        jumpToEndBoolean (opt ional) A Boolean indicat ing whether to complete the currentanimat ion immediately Defaults to false

        When stop() is called on an element the current ly-running animat ion (if any) is immediatelystopped If for instance an element is being hidden with slideUp() when stop() is called theelement will now st ill be displayed but will be a f ract ion of its previous height Callback funct ions

        are not called

        If more than one animat ion method is called on the same element the later animat ions areplaced in the ef fects queue for the element These animat ions will not begin unt il the f irst onecompletes When stop() is called the next animat ion in the queue begins immediately If theclearQueue parameter is provided with a value of t rue then the rest of the animat ions in thequeue are removed and never run

        If the jumpToEnd property is provided with a value of t rue the current animat ion stops but theelement is immediately given its target values for each CSS property In our above slideUp()example the element would be immediately hidden The callback funct ion is then immediatelycalled if provided

        The usefulness of the stop() method is evident when we need to animate an element onmouseenter and mouseleave

        ltdiv id=hovermegt Hover me ltimg id=hoverme src=bookpng alt= width=100 height=123 gtltdivgt

        We can create a nice fade ef fect without the common problem of mult iple queued animat ionsby adding stop(true t rue) to the chain

        $(hoverme-stop-2)hover(function() $(this)find( img)stop(true true)fadeOut() function() $(this)find( img)stop(true true)fadeIn())

        Animations may be stopped globally by setting the property $fxoff to true Whenthis is done all animation methods will immediately set elements to their finalstate when called rather than displaying an effect

        Example 1 Click the Go button once to start the animat ion then click the STOP button to stopit where it s current ly posit ioned Another opt ion is to click several buttons to queue them upand see that stop just kills the current ly playing one

        Javascript

        Start animation $(go)cl ick(function()$(block)animate(left +=100px 2000))

        Stop animation when button is cl icked $(stop)cl ick(function()$(block)stop())

        Start animation in the opposite direction $(back)cl ick(function()$(block)animate(left -=100px 2000))

        HTML

        ltbutton id=gogtGoltbuttongt ltbutton id=stopgtSTOPltbuttongtltbutton id=backgtBackltbuttongtltdiv class=blockgtltdivgt

        CSS

        div position absolute background-color abcleft 0pxtop30pxwidth 60px height 60pxmargin 5px

        animate

        Perform a custom animat ion of a set of CSS propert ies

        Added in version 10

        animate(propert ies opt ions)jQuery

        propert iesMap A map of CSS propert ies that the animat ion will move toward

        opt ionsMap A map of addit ional opt ions to pass to the method Supported keys

        durat ion A string or number determining how long theanimat ion will run

        easing A string indicat ing which easing funct ion to use for thetransit ion

        complete A funct ion to call once the animat ion is completestep A funct ion to be called af ter each step of the animat ionqueue A Boolean indicat ing whether to place the animat ion in

        the ef fects queue If false the animat ion will begin immediatelyspecialEasing A map of one or more of the CSS propert ies

        def ined by the propert ies argument and their correspondingeasing funct ions (added 14)

        The animate() method allows us to create animat ion ef fects on any numeric CSS property Theonly required parameter is a map of CSS propert ies This map is similar to the one that can besent to the css() method except that the range of propert ies is more restrict ive

        Animation Properties and Values

        All animated propert ies should be animated to a single numeric value except as noted belowmost propert ies that are non-numeric cannot be animated using basic jQuery funct ionality (Forexample width height or lef t can be animated but background-color cannot be) Propertyvalues are t reated as a number of pixels unless otherwise specif ied The units em and can bespecif ied where applicable

        In addit ion to style propert ies some non-style propert ies such as scrollTop and scrollLef t aswell as custom propert ies can be animated

        Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on

        In addit ion to numeric values each property can take the strings show hide and toggleThese shortcuts allow for custom hiding and showing animat ions that take into account thedisplay type of the element

        Animated propert ies can also be relat ive If a value is supplied with a leading += or -= sequenceof characters then the target value is computed by adding or subtract ing the given numberfrom the current value of the property

        Unlike shorthand animat ion methods such as slideDown() and fadeIn() the animate() methoddoes not make hidden elements visible as part of the ef fect For example given$(someElement )hide()animate(height20px 500) the animat ion will run but the element willremain hidden

        Duration

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        Complete Function

        If supplied the complete callback funct ion is f ired once the animat ion is complete This can beuseful for stringing dif ferent animat ions together in sequence The callback is not sent anyarguments but this is set to the DOM element being animated If mult iple elements areanimated the callback is executed once per matched element not once for the animat ion as awhole

        Basic Usage

        To animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 style=position relative left 10px gt

        To animate the opacity lef t of fset and height of the image simultaneously

        $(clickme)cl ick(function() $(book)animate( opacity 025 left +=50 height toggle 5000 function() Animation complete ))

        Note that the target value of the height property is toggle Since the image was visible beforethe animat ion shrinks the height to 0 to hide it A second click then reverses this t ransit ion

        The opacity of the image is already at its target value so this property is not animated by thesecond click Since the target value for lef t is a relat ive value the image moves even farther tothe right during this second animat ion

        Direct ional propert ies (top right bot tom lef t ) have no discernible ef fect on elements if theirposit ion style property is stat ic which it is by default

        Note The jQuery UI project extends the animate() method by allowing some non-numeric styles such as colors to be animated The project also includesmechanisms for specifying animations through CSS classes rather than individualattributes

        Note if attempting to animate an element with a height or width of 0px wherecontents of the element are visible due to overflow jQuery may clip this overflowduring animation By fixing the dimensions of the original element being hiddenhowever it is possible to ensure that the animation runs smoothly A clearfix canbe used to automatically fix the dimensions of your main element without the needto set this manually

        Step Function

        The second version of animate() provides a step opt ion acirceurordquo a callback funct ion that is f ired ateach step of the animat ion This funct ion is useful for enabling custom animat ion types oraltering the animat ion as it is occurring It accepts two arguments (now and fx) and this is setto the DOM element being animated

        now the numeric value of the property being animated at each step

        fx a reference to the jQueryfx prototype object which contains a number of propert iessuch as elem for the animated element start and end for the f irst and last value of theanimated property respect ively and prop for the property being animated

        Note that the step funct ion is called for each animated property on each animated element Forexample given two list items the step funct ion f ires four t imes at each step of the animat ion

        $( l i )animate( opacity 5 height 50 step function(now fx) var data = fxelemid + + fxprop + + now $(body)append(ltdivgt + data + ltdivgt) )

        Easing

        The remaining parameter of animate() is a string naming an easing funct ion to use An easingfunct ion specif ies the speed at which the animat ion progresses at dif ferent points within theanimat ion The only easing implementat ions in the jQuery library are the default called swingand one that progresses at a constant pace called linear More easing funct ions are availablewith the use of plug-ins most notably the jQuery UI suite

        Per-property Easing

        As of jQuery version 14 you can set per-property easing funct ions within a single animate()call In the f irst version of animate() each property can take an array as its value The f irstmember of the array is the CSS property and the second member is an easing funct ion If a per-property easing funct ion is not def ined for a part icular property it uses the value of theanimate() methods opt ional easing argument If the easing argument is not def ined thedefault swing funct ion is used

        For example to simultaneously animate the width and height with the swing easing funct ionand the opacity with the linear easing funct ion

        $(clickme)cl ick(function() $(book)animate( width [toggle swing] height [toggle swing] opacity toggle 5000 l inear function() $(this)after(ltdivgtAnimation completeltdivgt) ))

        In the second version of animate() the opt ions map can include the specialEasing propertywhich is itself a map of CSS propert ies and their corresponding easing funct ions For exampleto simultaneously animate the width using the linear easing funct ion and the height using the

        easeOutBounce easing funct ion

        $(clickme)cl ick(function() $(book)animate( width toggle height toggle duration 5000 specialEasing width l inear height easeOutBounce complete function() $(this)after(ltdivgtAnimation completeltdivgt) ))

        As previously noted a plugin is required for the easeOutBounce funct ion

        Example 1 Click the button to animate the div with a number of dif ferent propert ies

        Javascript

        Using multiple unit types within one animation

        $(go)cl ick(function() $(block)animate( width 70 opacity 04 marginLeft 06in fontSize 3em borderWidth 10px 1500 ))

        HTML

        ltbutton id=gogtampraquo Runltbuttongt

        ltdiv id=blockgtHelloltdivgt

        CSS

        div background-colorbcawidth100pxborder1px solid green

        Example 2 Animates a divs lef t property with a relat ive value Click several t imes on thebuttons to see the relat ive animat ions queued up

        Javascript

        $(right)cl ick(function() $(block)animate(left +=50px slow))

        $(left)cl ick(function() $(block)animate(left -=50px slow))

        HTML

        ltbutton id=leftgtamplaquoltbuttongt ltbutton id=rightgtampraquoltbuttongtltdiv class=blockgtltdivgt

        CSS

        div positionabsolute background-colorabc left50px width90px height90px margin5px

        Example 3 The f irst but ton shows how an unqueued animat ion works It expands the div out to90 width while the font-size is increasing Once the font-size change is complete the borderanimat ion will begin The second button starts a t radit ional chained animat ion where eachanimat ion will start once the previous animat ion on the element has completed

        Javascript

        $( go1 )cl ick(function() $( block1 )animate( width 90 queue false duration 3000 ) animate( fontSize 24px 1500 ) animate( borderRightWidth 15px 1500 ))

        $( go2 )cl ick(function() $( block2 )animate( width 90 1000 ) animate( fontSize 24px 1000 ) animate( borderLeftWidth 15px 1000 ))

        $( go3 )cl ick(function() $( go1 )add( go2 )cl ick())

        $( go4 )cl ick(function() $( div )css( width fontSize borderWidth ))

        HTML

        ltbutton id=go1gtampraquo Animate Block1ltbuttongtltbutton id=go2gtampraquo Animate Block2ltbuttongtltbutton id=go3gtampraquo Animate Bothltbuttongt

        ltbutton id=go4gtampraquo Resetltbuttongtltdiv id=block1gtBlock1ltdivgtltdiv id=block2gtBlock2ltdivgt

        CSS

        div background-colorbca width200px height11em text-aligncenter border2px solid green margin3px font-size14pxbutton font-size14px

        Example 4 Animates the f irst divs lef t property and synchronizes the remaining divs using thestep funct ion to set their lef t propert ies at each stage of the animat ion

        Javascript

        $( go )cl ick(function() $( blockfirst )animate( left 100 duration 1000 step function( now fx ) $( blockgt(0) )css( left now ) ))

        CSS

        div position relative background-color abc width 40px height 40px float left margin 5px

        HTML

        ltpgtltbutton id=gogtRun Acircraquoltbuttongtltpgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgtltdiv class=blockgtltdivgt ltdiv class=blockgtltdivgt

        Example 5 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

        Javascript

        $( p )animate( height toggle opacity toggle slow )

        Example 6 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds

        Javascript

        $( p )animate( left 50 opacity 1 500 )

        Example 7 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion Note this code will donothing unless the paragraph element is hidden

        Javascript

        $( p )animate( opacity show slow easein )

        Example 8 Animates all paragraphs to toggle both height and opacity complet ing theanimat ion within 600 milliseconds

        Javascript

        $( p )animate( height toggle opacity toggle duration slow )

        Example 9 Animates all paragraph to a lef t style of 50 and opacity of 1 (opaque visible)complet ing the animat ion within 500 milliseconds It also will do it outside the queue meaning itwill automat ically start without wait ing for its turn

        Javascript

        $( p )animate( left 50px opacity 1 duration 500 queue false )

        Example 10 An example of using an easing funct ion to provide a dif ferent style of animat ionThis will only work if you have a plugin that provides this easing funct ion

        Javascript

        $( p )animate( opacity show duration slow easing easein )

        Example 11 An example of using a callback funct ion The f irst argument is an array of CSSpropert ies the second specif ies that the animat ion should take 1000 milliseconds to completethe third states the easing type and the fourth argument is an anonymous callback funct ion

        Javascript

        $( p )animate( height200 width400 opacity 5 1000 l inear function() alert(all done) )

        fadeTo

        Adjust the opacity of the matched elements

        Added in version 143

        fadeTo(durat ion opacity easing callback)jQuery

        durat ionStringNumber A string or number determining how long the animat ion will run

        opacityNumber A number between 0 and 1 denot ing the target opacity

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The fadeTo() method animates the opacity of the matched elements

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied the default durat ion of 400 milliseconds is usedUnlike the other ef fect methods fadeTo() requires that durat ion be explicit ly specif ied

        If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly shown we can dim it slowly $(clickme)cl ick(function() $(book)fadeTo(slow 05 function() Animation complete ) )

        With durat ion set to 0 this method just changes the opacity CSSproperty so fadeTo(0 opacity) is the same as css(opacity opacity)

        Example 1 Animates f irst paragraph to fade to an opacity of 033 (33about one third visible) complet ing the animat ion within 600milliseconds

        Javascript

        $(pfirst)cl ick(function () $(this)fadeTo(slow 033))

        HTML

        ltpgtClick this paragraph to see it fadeltpgt

        ltpgtCompare to this one that wont fadeltpgt

        Example 2 Fade div to a random opacity on each click complet ing theanimat ion within 200 milliseconds

        Javascript

        $(div)cl ick(function () $(this)fadeTo(fast Mathrandom()))

        CSS

        p width80px margin0 padding5px div width40px height40px positionabsolute divone top0 left0 backgroundf00 divtwo top20px left20px background0f0 divthree top40px left40px background00f

        HTML

        ltpgtAnd this is the l ibrary that John builtltpgt

        ltdiv id=onegtltdivgtltdiv id=twogtltdivgtltdiv id=threegtltdivgt

        Example 3 Find the right answer The fade will take 250 milliseconds andchange various styles when it completes

        Javascript

        var getPos = function (n) return (Mathfloor(n) 90) + px$(p)each(function (n) var r = Mathfloor(Mathrandom() 3)var tmp = $(this)text()$(this)text($(peq( + r + ))text())$(peq( + r + ))text(tmp)$(this)css(left getPos(n)))$(div)each(function (n) $(this)css(left getPos(n)) )css(cursor pointer)cl ick(function () $(this)fadeTo(250 025 function () $(this)css(cursor ) prev()css(font-weight bolder font-style ital ic) ) )

        CSS

        div p width80px height40px top0 margin0 positionabsolute padding-top8px p backgroundfcc text-aligncenter div backgroundblue

        HTML

        ltpgtWrongltpgtltdivgtltdivgtltpgtWrongltpgtltdivgtltdivgt

        ltpgtRightltpgtltdivgtltdivgt

        fadeOut

        Hide the matched elements by fading them to t ransparent

        Added in version 143

        fadeOut(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The fadeOut() method animates the opacity of the matched elements Once the opacityreaches 0 the display style property is set to none so the element no longer af fects the layoutof the page

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

        With the element init ially shown we can hide it slowly

        $(clickme)cl ick(function() $(book)fadeOut(slow function() Animation complete ))

        Note To avoid unnecessary DOM manipulation fadeOut() willnot hide an element that is already considered hidden Forinformation on which elements jQuery considers hidden seehidden Selector

        Easing

        As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

        As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

        Example 1 Animates all paragraphs to fade out complet ing theanimat ion within 600 milliseconds

        Javascript

        $(p)cl ick(function () $(p)fadeOut(slow) )

        CSS

        p font-size150 cursorpointer

        HTML

        ltpgt If you click on this paragraph youl l see it just fade away ltpgt

        Example 2 Fades out spans in one sect ion that you click on

        Javascript

        $(span)cl ick(function () $(this)fadeOut(1000 function () $(div)text( + $(this)text() + has faded) $(this)remove() ) ) $(span)hover(function () $(this)addClass(hil ite) function () $(this)removeClass(hil ite) )

        CSS

        span cursorpointer spanhil ite backgroundyellow div displayinline colorred

        HTML

        lth3gtFind the modifiers - ltdivgtltdivgtlth3gt ltpgt If you ltspangtreallyltspangt want to go outside ltspangtin the coldltspangt then make sure to wear your ltspangtwarmltspangt jacket given to you by your ltspangtfavoriteltspangt teacher ltpgt

        Example 3 Fades out two divs one with a linear easing and one with the default swingeasing

        Javascript

        $(btn1)cl ick(function() function complete() $(ltdivgt)text(thisid)appendTo(log) $(box1)fadeOut(1600 l inear complete) $(box2)fadeOut(1600 complete))

        $(btn2)cl ick(function() $(div)show() $(log)empty())

        CSS

        boxbutton floatleft margin5px 10px 5px 0 box height80px width80px background090 log clearleft

        HTML

        ltbutton id=btn1gtfade outltbuttongtltbutton id=btn2gtshowltbuttongt

        ltdiv id=loggtltdivgt

        ltdiv id=box1 class=boxgtlinearltdivgtltdiv id=box2 class=boxgtswingltdivgt

        fadeIn

        Display the matched elements by fading them to opaque

        Added in version 143

        fadeIn(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The fadeIn() method animates the opacity of the matched elements

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click here ltdivgt ltimg id=book src=bookpng alt= width=100 height=123 gt With the element initial ly hidden we can show it slowly $(clickme)cl ick(function() $(book)fadeIn(slow function() Animation complete ) )

        Easing

        As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

        As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

        Example 1 Animates hidden divs to fade in one by one complet ing eachanimat ion within 600 milliseconds

        Javascript

        $(documentbody)cl ick(function () $(divhiddenfirst)fadeIn(slow) )

        CSS

        span colorred cursorpointer div margin3px width80px displaynone height80px floatleft divone backgroundf00 divtwo background0f0 divthree background00f

        HTML

        ltspangtClick hereltspangt

        ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt

        Example 2 Fades a red block in over the text Once the animat ion is done it quickly fades inmore text on top

        Javascript

        $(a)cl ick(function () $(div)fadeIn(3000 function () $(span)fadeIn(100) ) return false )

        CSS

        p positionrelative width400px height90px div positionabsolute width400px height65px font-size36px text-aligncenter coloryellow backgroundred padding-top25px top0 left0 displaynone span displaynone

        HTML

        ltpgt 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 (lta href=gtclickltagt) ltdivgtltspangtCENSOREDltspangtltdivgt

        ltpgt

        slideToggle

        Display or hide the matched elements with a sliding mot ion

        Added in version 143

        slideToggle(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The slideToggle() method animates the height of the matched elements This causes lowerparts of the page to slide up or down appearing to reveal or conceal the items If the element isinit ially displayed it will be hidden if hidden it will be shown The display property is saved andrestored as needed If an element has a display value of inline then is hidden and shown it willonce again be displayed inline When the height reaches 0 af ter a hiding animat ion the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster ones

        The strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

        We will cause slideToggle() to be called when another element is clicked

        $(clickme)cl ick(function() $(book)sl ideToggle(slow function() Animation complete ))

        With the element init ially shown we can hide it slowly with the f irst click

        A second click will show the element once again

        Easing

        As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

        As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed their

        animat ions ( See the example for promise() )

        Example 1 Animates all paragraphs to slide up or down complet ing theanimat ion within 600 milliseconds

        Javascript

        $(button)cl ick(function () $(p)sl ideToggle(slow) )

        CSS

        p width400px

        HTML

        ltbuttongtToggleltbuttongt

        ltpgt This is the paragraph to end all paragraphs You should feel ltemgtluckyltemgt to have seen such a paragraph in your l i fe Congratulations ltpgt

        Example 2 Animates divs between dividers with a toggle that makessome appear and some disappear

        Javascript

        $(aa)cl ick(function () $(divnot(sti l l))sl ideToggle(slow function () var n = parseInt($(span)text() 10) $(span)text(n + 1) ) )

        CSS

        div backgroundb977d1 margin3px width60px height60px floatleft divsti l l background345 width5px divhider displaynone span colorred p clear left

        HTML

        ltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv style=displaynonegtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdiv class=hidergtltdivgtltdiv class=sti l lgtltdivgtltdivgtltdivgtltpgtltbutton id=aagtToggleltbuttongt There have been ltspangt0ltspangt toggled divsltpgt

        slideUp

        Hide the matched elements with a sliding mot ion

        Added in version 143

        slideUp(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The slideUp() method animates the height of the matched elements This causes lower partsof the page to slide up appearing to conceal the items Once the height reaches 0 the displaystyle property is set to none to ensure that the element no longer af fects the layout of thepage

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

        With the element init ially shown we can hide it slowly

        $(clickme)cl ick(function() $(book)sl ideUp(slow function() Animation complete ))

        Easing

        As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

        As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

        Example 1 Animates all divs to slide up complet ing the animat ion within400 milliseconds

        Javascript

        $(documentbody)cl ick(function () i f ($(divfirst)is(hidden)) $(div)show(slow) else $(div)sl ideUp() )

        CSS

        div background3d9a44 margin3px width80px height40px floatleft

        HTML

        Click me ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt

        ltdivgtltdivgt

        Example 2 Animates the parent paragraph to slide up complet ing the animat ion within 200milliseconds Once the animat ion is done it displays an alert

        Javascript

        $(button)cl ick(function () $(this)parent()sl ideUp(slow function () $(msg)text($(button this)text() + has completed) ) )

        CSS

        div margin2px

        HTML

        ltdivgt ltbuttongtHide Oneltbuttongt ltinput type=text value=One gt

        ltdivgtltdivgt ltbuttongtHide Twoltbuttongt ltinput type=text value=Two gt

        ltdivgtltdivgt ltbuttongtHide Threeltbuttongt ltinput type=text value=Three gt

        ltdivgtltdiv id=msggtltdivgt

        slideDown

        Display the matched elements with a sliding mot ion

        Added in version 143

        slideDown(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        The slideDown() method animates the height of the matched elements This causes lowerparts of the page to slide down making way for the revealed items

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively If any other string is supplied or if the durat ion parameter is omit ted the defaultdurat ion of 400 milliseconds is used

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

        With the element init ially hidden we can show it slowly

        $(clickme)cl ick(function() $(book)sl ideDown(slow function() Animation complete ))

        Easing

        As of jQuery 143 an opt ional string naming an easing funct ion may beused Easing funct ions specify the speed at which the animat ionprogresses at dif ferent points within the animat ion The only easingimplementat ions in the jQuery library are the default called swing andone that progresses at a constant pace called linear More easingfunct ions are available with the use of plug-ins most notably the jQueryUI suite

        Callback Function

        If supplied the callback is f ired once the animat ion is complete This canbe useful for stringing dif ferent animat ions together in sequence Thecallback is not sent any arguments but this is set to the DOM elementbeing animated If mult iple elements are animated it is important to notethat the callback is executed once per matched element not once forthe animat ion as a whole

        As of jQuery 16 the promise() method can be used in conjunct ion withthe deferreddone() method to execute a single callback for theanimat ion as a whole when all matching elements have completed theiranimat ions ( See the example for promise() )

        Example 1 Animates all divs to slide down and show themselves over600 milliseconds

        Javascript

        $(documentbody)cl ick(function () if ($(divfirst)is(hidden)) $(div)sl ideDown(slow) else $(div)hide())

        CSS

        div backgroundde9a44 margin3px width80px height40px displaynone floatleft

        HTML

        Click meltdivgtltdivgtltdivgtltdivgtltdivgtltdivgt

        Example 2 Animates all inputs to slide down complet ing the animat ion within 1000milliseconds Once the animat ion is done the input look is changed especially if it is the middleinput which gets the focus

        Javascript

        $(div)cl ick(function () $(this)css( borderStyleinset cursorwait )$(input)sl ideDown(1000function()$(this)css(border 2px red inset)fi lter(middle) css(background yellow) focus()$(div)css(visibil ity hidden)))

        CSS

        div backgroundcfd margin3px width50px text-aligncenter floatleft cursorpointerborder2px outset black font-weightbolder input displaynone width120px floatleft margin10px

        HTML

        ltdivgtPushltdivgtltinput type=text gtltinput type=text class=middle gt

        ltinput type=text gt

        toggle

        Display or hide the matched elements

        Added in version 13

        toggle(showOrHide)jQuery

        showOrHideBoolean A Boolean indicat ing whether to show or hide the elements

        With no parameters the toggle() method simply toggles the visibility of elements

        $(target)toggle()

        The matched elements will be revealed or hidden immediately with no animat ion by changingthe CSS display property If the element is init ially displayed it will be hidden if hidden it will beshown The display property is saved and restored as needed If an element has a display valueof inline then is hidden and shown it will once again be displayed inline

        When a durat ion is provided toggle() becomes an animat ion method The toggle() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 af ter a hiding animat ion the display style property is set to none to ensurethat the element no longer af fects the layout of the page

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        Note The event handling suite also has a method named toggle() Which one isfired depends on the set of arguments passed

        As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use of

        plug-ins most notably the jQuery UI suite

        If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gt

        We will cause toggle() to be called when another element is clicked

        $(clickme)cl ick(function() $(book)toggle(slow function() Animation complete ))

        With the element init ially shown we can hide it slowly with the f irst click

        A second click will show the element once again

        The second version of the method accepts a Boolean parameter If thisparameter is t rue then the matched elements are shown if false theelements are hidden In essence the statement

        $(foo)toggle(showOrHide)

        is equivalent to

        i f ( showOrHide == true ) $(foo)show() else if ( showOrHide == false ) $(foo)hide()

        Example 1 Toggles all paragraphs

        Javascript

        $(button)cl ick(function () $(p)toggle())

        HTML

        ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

        Example 2 Animates all paragraphs to be shown if they are hidden andhidden if they are visible complet ing the animat ion within 600milliseconds

        Javascript

        $(button)cl ick(function () $(p)toggle(slow))

        CSS

        p backgrounddadfont-weightboldfont-size16px

        HTML

        ltbuttongtToggle emltbuttongt

        ltpgtHiyaltpgtltpgtSuch interesting text ehltpgt

        Example 3 Shows all paragraphs then hides them all back and forth

        Javascript

        var fl ip = 0$(button)cl ick(function () $(p)toggle( fl ip++ 2 == 0 ))

        HTML

        ltbuttongtToggleltbuttongtltpgtHelloltpgtltp style=display nonegtGood Byeltpgt

        hide

        Hide the matched elements

        Added in version 143

        hide(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determininghow long the animat ion will run

        easingString (opt ional) A string indicat ing whicheasing funct ion to use for the t ransit ion

        callbackCallback (opt ional) A funct ion to call once theanimat ion is complete

        With no parameters the hide() method is the simplest way to hide an element

        $(target)hide()

        The matched elements will be hidden immediately with no animat ion This is roughly equivalentto calling css(display none) except that the value of the display property is saved in jQuerysdata cache so that display can later be restored to its init ial value If an element has a displayvalue of inline then is hidden and shown it will once again be displayed inline

        When a durat ion is provided hide() becomes an animat ion method The hide() methodanimates the width height and opacity of the matched elements simultaneously When thesepropert ies reach 0 the display style property is set to none to ensure that the element nolonger af fects the layout of the page

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

        If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly shown we can hide it slowly$(clickme)cl ick(function() $(book)hide(slow function() alert(Animation complete) ))

        Example 1 Hides all paragraphs then the link on click

        Javascript

        $(p)hide() $(a)cl ick(function ( event ) eventpreventDefault() $(this)hide() )

        HTML

        ltpgtHelloltpgt lta href=gtClick to hide me tooltagt ltpgtHere is another paragraphltpgt

        Example 2 Animates all shown paragraphs to hide slowly complet ingthe animat ion within 600 milliseconds

        Javascript

        $(button)cl ick(function () $(p)hide(slow) )

        CSS

        p backgrounddad font-weightbold

        HTML

        ltbuttongtHide emltbuttongt

        ltpgtHiyaltpgt ltpgtSuch interesting text ehltpgt

        Example 3 Animates all spans (words in this case) to hide fast ly complet ing each animat ionwithin 200 milliseconds Once each animat ion is done it starts the next one

        Javascript

        $(hidr)cl ick(function () $(spanlast-child)hide(fast function () use callee so dont have to name the function $(this)prev()hide(fast argumentscallee) ) ) $(showr)cl ick(function () $(span)show(2000) )

        CSS

        span backgrounddef3ca padding3px floatleft

        HTML

        ltbutton id=hidrgtHideltbuttongt ltbutton id=showrgtShowltbuttongt ltdivgt

        ltspangtOnceltspangt ltspangtuponltspangt ltspangtaltspangt ltspangttimeltspangt ltspangtthereltspangt ltspangtwereltspangt ltspangtthreeltspangt ltspangtprogrammersltspangt

        ltdivgt

        Example 4 Hides the divs when clicked over 2 seconds then removes the div element when itshidden Try clicking on more than one box at a t ime

        Javascript

        for (var i = 0 i lt 5 i++) $(ltdivgt)appendTo(documentbody) $(div)cl ick(function () $(this)hide(2000 function () $(this)remove() ) )

        CSS

        div backgroundece023 width30px height40px margin2px floatleft

        HTML

        ltdivgtltdivgt

        show

        Display the matched elements

        Added in version 143

        show(durat ion easing callback)jQuery

        durat ionStringNumber (opt ional) A string or number determining how long theanimat ion will run

        easingString (opt ional) A string indicat ing which easing funct ion to use forthe transit ion

        callbackCallback (opt ional) A funct ion to call once the animat ion is complete

        With no parameters the show() method is the simplest way to display an element

        $(target)show()

        The matched elements will be revealed immediately with no animat ion This is roughlyequivalent to calling css(display block) except that the display property is restored towhatever it was init ially If an element has a display value of inline then is hidden and shown itwill once again be displayed inline

        Note If using important in your styles such as display none important it is necessary tooverride the style using css(display block important ) should you wish for show() to funct ioncorrect ly

        When a durat ion is provided show() becomes an animat ion method The show() methodanimates the width height and opacity of the matched elements simultaneously

        Durat ions are given in milliseconds higher values indicate slower animat ions not faster onesThe strings fast and slow can be supplied to indicate durat ions of 200 and 600 millisecondsrespect ively

        As of jQuery 143 an opt ional string naming an easing funct ion may be used Easing funct ionsspecify the speed at which the animat ion progresses at dif ferent points within the animat ionThe only easing implementat ions in the jQuery library are the default called swing and one thatprogresses at a constant pace called linear More easing funct ions are available with the use ofplug-ins most notably the jQuery UI suite

        If supplied the callback is f ired once the animat ion is complete This can be useful for stringingdif ferent animat ions together in sequence The callback is not sent any arguments but this isset to the DOM element being animated If mult iple elements are animated it is important tonote that the callback is executed once per matched element not once for the animat ion as awhole

        We can animate any element such as a simple image

        ltdiv id=clickmegt Click hereltdivgtltimg id=book src=bookpng alt= width=100 height=123 gtWith the element initial ly hidden we can show it slowly$(clickme)cl ick(function() $(book)show(slow function() Animation complete ))

        Example 1 Animates all hidden paragraphs to show slowly complet ingthe animat ion within 600 milliseconds

        Javascript

        $(button)cl ick(function () $(p)show(slow) )

        CSS

        p backgroundyellow

        HTML

        ltbuttongtShow itltbuttongt

        ltp style=display nonegtHello 2ltpgt

        Example 2 Animates all hidden divs to show fast ly in order complet ingeach animat ion within 200 milliseconds Once each animat ion is done itstarts the next one

        Javascript

        $(showr)cl ick(function () $(diveq(0))show(fast function () use callee so dont have to name the function $(this)next(div)show(fast argumentscallee) ))$(hidr)cl ick(function () $(div)hide(2000))

        CSS

        div backgrounddef3ca margin3px width80px displaynone floatleft text-aligncenter

        HTML

        ltbutton id=showrgtShowltbuttongt ltbutton id=hidrgtHideltbuttongt ltdivgtHello 3ltdivgt

        ltdivgthowltdivgt ltdivgtareltdivgt ltdivgtyoultdivgt

        Example 3 Shows all span and input elements with an animat ion Once the animat ion is done itchanges the text

        Javascript

        function doIt() $(spandiv)show(slow) can pass in function name $(button)cl ick(doIt)

        $(form)submit(function () if ($(input)val() == yes) $(p)show(4000 function () $(this)text(Ok DONE (now showing)) ) $(spandiv)hide(fast) to stop the submit return false )

        CSS

        span displaynone div displaynone p font-weightbold background-colorfcd

        HTML

        ltbuttongtDo itltbuttongt ltspangtAre you sure (type yes if you are) ltspangt ltdivgt ltformgt ltinput type=text value=asldkfjalsdfgt ltformgt ltdivgt ltp style=displaynonegtIm hiddenltpgt

        Ajax

        jQueryajaxPrefilter

        Handle custom Ajax opt ions or modify exist ing opt ions before each request is sent and beforethey are processed by $ajax()

        Added in version 15

        jQueryajaxPref ilter(dataTypes handler(opt ions originalOpt ions jqXHR))undef ined

        dataTypesString (opt ional) An opt ional string containing one or more

        space-separated dataTypes

        handler(opt ionsoriginalOpt ionsjqXHR)Funct ion

        A handler to set default values for future Ajaxrequests

        A typical pref ilter registrat ion using $ajaxPref ilter() looks like this

        $ajaxPrefi lter( function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

        where

        opt ions are the request opt ions

        originalOpt ions are the opt ions as provided to the ajax method unmodif ied and thuswithout defaults f rom ajaxSett ings

        jqXHR is the jqXHR object of the request

        Pref ilters are a perfect f it when custom opt ions need to be handled Given the following codefor example a call to $ajax() would automat ically abort a request to the same URL if thecustom abortOnRetry opt ion is set to t rue

        var currentRequests =

        $ajaxPrefi lter(function( options originalOptions jqXHR ) if ( optionsabortOnRetry ) i f ( currentRequests[ optionsurl ] ) currentRequests[ optionsurl ]abort() currentRequests[ optionsurl ] = jqXHR )

        Pref ilters can also be used to modify exist ing opt ions For example the following proxies cross-domain requests through ht tpmydomainnetproxy

        $ajaxPrefi lter( function( options ) if ( optionscrossDomain ) optionsurl = httpmydomainnetproxy + encodeURIComponent( optionsurl ) optionscrossDomain = false )

        If the opt ional dataTypes argument is supplied the pref ilter will be only be applied to requestswith the indicated dataTypes For example the following only applies the given pref ilter toJSON and script requests

        $ajaxPrefi lter( json script function( options originalOptions jqXHR ) Modify options control originalOptions store jqXHR etc)

        The $ajaxPref ilter() method can also redirect a request to another dataType by returning thatdataType For example the following sets a request as script if the URL has some specif icpropert ies def ined in a custom isActuallyScript() funct ion

        $ajaxPrefi lter(function( options ) if ( isActuallyScript( optionsurl ) ) return script )

        This would ensure not only that the request is considered script but also that all the pref iltersspecif ically at tached to the script dataType would be applied to it

        ajaxComplete

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

        Added in version 10

        ajaxComplete(handler(event XMLHttpRequest ajaxOpt ions))jQuery

        handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

        Whenever an Ajax request completes jQuery t riggers the ajaxComplete event Any and allhandlers that have been registered with the ajaxComplete() method are executed at this t ime

        To observe this method in act ion we can set up a basic Ajax load request

        ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

        When the user clicks the button and the Ajax request completes the log message is displayed

        Note Because ajaxComplete() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

        All ajaxComplete handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxComplete handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

        Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

        $(log)ajaxComplete(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxComplete handler The result is + xhrresponseHTML) )

        Example 1 Show a message when an Ajax request completes

        Javascript

        $(msg)ajaxComplete(function(eventrequest settings) $(this)append(ltligtRequest Completeltl igt) )

        serializeArray see Forms

        serialize see Forms

        jQueryajaxSetup

        Set default values for future Ajax requests

        Added in version 11

        jQueryajaxSetup(opt ions)

        opt ionsOpt ions A set of keyvalue pairs that conf igure the default Ajax request Allopt ions are opt ional

        For details on the sett ings available for $ajaxSetup() see $ajax()

        All subsequent Ajax calls using any funct ion will use the new sett ings unless overridden by theindividual calls unt il the next invocat ion of $ajaxSetup()

        For example the following sets a default for the url parameter before pinging the serverrepeatedly

        $ajaxSetup( url pingphp)

        Now each t ime an Ajax request is made the pingphp URL will be used automat ically

        $ajax( url not set here uses pingphp data name Dan)

        Note Global callback functions should be set with their respective global Ajaxevent handler methodsacirceurordquoajaxStart() ajaxStop() ajaxComplete() ajaxError()ajaxSuccess() ajaxSend()acirceurordquorather than within the options object for$ajaxSetup()

        Example 1 Sets the defaults for Ajax requests to the url xmlht tp disables global handlersand uses POST instead of GET The following Ajax requests then sends some data withouthaving to set anything else

        Javascript

        $ajaxSetup( url xmlhttp global false type POST

        ) $ajax( data myData )

        ajaxSuccess

        Attach a funct ion to be executed whenever an Ajax request completes successfully This is anAjax Event

        Added in version 10

        ajaxSuccess(handler(event XMLHttpRequest ajaxOpt ions))jQuery

        handler(event XMLHttpRequest ajaxOpt ions)Funct ion The funct ion to be invoked

        Whenever an Ajax request completes successfully jQuery t riggers the ajaxSuccess event Anyand all handlers that have been registered with the ajaxSuccess() method are executed at thist ime

        To observe this method in act ion we can set up a basic Ajax load request

        ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

        When the user clicks the button and the Ajax request completes successfully the log messageis displayed

        Note Because ajaxSuccess() is implemented as a method of jQuery object instances we canuse the this keyword as we do here to refer to the selected elements within the callbackfunct ion

        All ajaxSuccess handlers are invoked regardless of what Ajax request was completed If wemust dif ferent iate between the requests we can use the parameters passed to the handlerEach t ime an ajaxSuccess handler is executed it is passed the event object theXMLHttpRequest object and the sett ings object that was used in the creat ion of the requestFor example we can restrict our callback to only handling events dealing with a part icular URL

        Note You can get the returned ajax contents by looking at xhrresponseXML orxhrresponseHTML for xml and html respect ively

        $(log)ajaxSuccess(function(e xhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSuccess handler The ajax response was + xhrresponseHTML ) )

        Example 1 Show a message when an Ajax request completes successfully

        Javascript

        $(msg)ajaxSuccess(function(evt request settings) $(this)append(ltligtSuccessful Requestltl igt) )

        ajaxStop

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

        Added in version 10

        ajaxStop(handler())jQuery

        handler()Funct ion The funct ion to be invoked

        Whenever an Ajax request completes jQuery checks whether there are any other outstandingAjax requests If none remain jQuery t riggers the ajaxStop event Any and all handlers that havebeen registered with the ajaxStop() method are executed at this t ime The ajaxStop event isalso t riggered if the last outstanding Ajax request is cancelled by returning false within thebeforeSend callback funct ion

        To observe this method in act ion we can set up a basic Ajax load request

        ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

        When the user clicks the button and the Ajax request completes the log message is displayed

        Because ajaxStop() is implemented as a method of jQuery object instances we can use thethis keyword as we do here to refer to the selected elements within the callback funct ion

        Example 1 Hide a loading message af ter all the Ajax requests have stopped

        Javascript

        $(loading)ajaxStop(function() $(this)hide() )

        ajaxStart

        Register a handler to be called when the f irst Ajax request begins This is an Ajax Event

        Added in version 10

        ajaxStart(handler())jQuery

        handler()Funct ion The funct ion to be invoked

        Whenever an Ajax request is about to be sent jQuery checks whether there are any otheroutstanding Ajax requests If none are in progress jQuery t riggers the ajaxStart event Any andall handlers that have been registered with the ajaxStart() method are executed at this t ime

        To observe this method in act ion we can set up a basic Ajax load request

        ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

        When the user clicks the button and the Ajax request is sent the log message is displayed

        Note Because ajaxStart() is implemented as a method of jQuery object instances we can usethe this keyword as we do here to refer to the selected elements within the callback funct ion

        Example 1 Show a loading message whenever an Ajax request starts (and none is alreadyact ive)

        Javascript

        $(loading)ajaxStart(function() $(this)show() )

        ajaxSend

        Attach a funct ion to be executed before an Ajax request is sent This is an Ajax Event

        Added in version 10

        ajaxSend(handler(event jqXHR ajaxOpt ions))jQuery

        handler(event jqXHR ajaxOpt ions)Funct ion The funct ion to be invoked

        Whenever an Ajax request is about to be sent jQuery t riggers the ajaxSend event Any and allhandlers that have been registered with the ajaxSend() method are executed at this t ime

        To observe this method in act ion we can set up a basic Ajax load request

        ltdiv class=triggergtTriggerltdivgtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        We can at tach 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)cl ick(function() $( result)load(ajaxtesthtml))

        When the user clicks the button and the Ajax request is about to begin the log message isdisplayed

        Note Because ajaxSend() is implemented as a method of jQuery instances we can use the thiskeyword as we do here to refer to the selected elements within the callback funct ion

        All ajaxSend handlers are invoked regardless of what Ajax request is to be sent If we mustdif ferent iate between the requests we can use the parameters passed to the handler Eacht ime an ajaxSend handler is executed it is passed the event object the jqXHR object (in version14 XMLHttpRequestobject) and the sett ings object that was used in the creat ion of the Ajaxrequest For example we can restrict our callback to only handling events dealing with apart icular URL

        $(log)ajaxSend(function(e jqxhr settings) if (settingsurl == ajaxtesthtml) $(this)text(Triggered ajaxSend handler) )

        Example 1 Show a message before an Ajax request is sent

        Javascript

        $(msg)ajaxSend(function(evt request settings) $(this)append(ltligtStarting request at + settingsurl + ltl igt) )

        ajaxError

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

        Added in version 10

        ajaxError(handler(event jqXHR ajaxSett ings thrownError))jQuery

        handler(event jqXHR ajaxSett ings thrownError)Funct ion The funct ion to be invoked

        Whenever an Ajax request completes with an error jQuery t riggers the ajaxError event Any andall handlers that have been registered with the ajaxError() method are executed at this t ime

        To observe this method in act ion set up a basic Ajax load request

        ltbutton class=triggergtTriggerltbuttongtltdiv class=resultgtltdivgtltdiv class=loggtltdivgt

        Attach the event handler to any element

        $(divlog)ajaxError(function() $(this)text( Triggered ajaxError handler ))

        Now make an Ajax request using any jQuery method

        $(buttontrigger)cl ick(function() $(divresult)load( ajaxmissinghtml ))

        When the user clicks the button and the Ajax request fails because the requested f ile ismissing the log message is displayed

        Note Because ajaxError() is implemented as a method of jQuery object instances you can usethe this keyword within the callback funct ion to refer to the selected elements

        All ajaxError handlers are invoked regardless of what Ajax request was completed Todif ferent iate between the requests you can use the parameters passed to the handler Eacht ime an ajaxError handler is executed it is passed the event object the jqXHR object (prior tojQuery 15 the XHR object) and the sett ings object that was used in the creat ion of the

        request If the request failed because JavaScript raised an except ion the except ion object ispassed to the handler as a fourth parameter For example to restrict the error callback to onlyhandling events dealing with a part icular URL

        $( divlog )ajaxError(function(e jqxhr settings exception) if ( settingsurl == ajaxmissinghtml ) $(this)text( Triggered ajaxError handler ) )

        Example 1 Show a message when an Ajax request fails

        Javascript

        $(msg)ajaxError(function(event request settings) $(this)append(ltligtError requesting page + settingsurl + ltl igt))

        jQuerypost

        Load data f rom the server using a HTTP POST request

        Added in version 10

        jQuerypost(url data success(data textStatus jqXHR) dataType)jqXHR

        urlString A string containing the URL to which the request is sent

        dataMap String (opt ional) A map or string that is sent to the server with therequest

        success(datatextStatusjqXHR)Funct ion

        (opt ional) A callback funct ion that is executed if the requestsucceeds

        dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

        This is a shorthand Ajax funct ion which is equivalent to

        $ajax( type POST url url data data success success dataType dataType)

        The success callback funct ion is passed the returned data which will be an XML root elementor a text string depending on the MIME type of the response It is also passed the text statusof the response

        As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object)

        Most implementat ions will specify a success handler

        $post(ajaxtesthtml function(data) $( result)html(data))

        This example fetches the requested HTML snippet and inserts it on the page

        Pages fetched with POST are never cached so the cache and ifModif ied opt ions injQueryajaxSetup() have no ef fect on these requests

        The jqXHR Object

        As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $post() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

        The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $post() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

        Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $post(examplephp 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 jqxhrcomplete(function() alert(second complete) )

        Example 1 Request the test php page but ignore the return results

        Javascript

        $post(testphp)

        Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

        Javascript

        $post(testphp name John time 2pm )

        Example 3 pass arrays of data to the server (while st ill ignoring the return results)

        Javascript

        $post(testphp choices[] [ Jon Susan] )

        Example 4 send form data using ajax requests

        Javascript

        $post(testphp $(testform)serial ize())

        Example 5 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

        Javascript

        $post(testphp function(data) alert(Data Loaded + data) )

        Example 6 Alert out the results f rom request ing test php with an addit ional payload of data(HTML or XML depending on what was returned)

        Javascript

        $post(testphp name John time 2pm function(data) alert(Data Loaded + data) )

        Example 7 Gets the test php page content store it in a XMLHttpResponse object and appliesthe process() JavaScript funct ion

        Javascript

        $post(testphp name John time 2pm function(data) process(data) xml)

        Example 8 Posts to the test php page and gets contents which has been returned in jsonformat (Johnt ime=gt2pm)) gt)

        Javascript

        $post(testphp func getNameAndTime function(data) consolelog(dataname) John consolelog(datatime) 2pm json)

        Example 9 Post a form using ajax and put results in a div

        Javascript

        attach a submit handler to the form $(searchForm)submit(function(event)

        stop form from submitting normally eventpreventDefault() get some values from elements on the page var $form = $( this ) term = $formfind( input[name=s] )val() url = $formattr( 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 )empty()append( content ) ) )

        HTML

        ltform action= id=searchFormgt ltinput type=text name=s placeholder=Search gt ltinput type=submit value=Search gt ltformgt lt-- the result of the search wil l be rendered inside this div --gt ltdiv id=resultgtltdivgt

        jQuerygetScript

        Load a JavaScript f ile f rom the server using a GET HTTP request then execute it

        Added in version 10

        jQuerygetScript(url success(data textStatus))jqXHR

        urlString A string containing the URL to which the request is sent

        success(datatextStatus)Funct ion

        (opt ional) A callback funct ion that is executed if therequest succeeds

        This is a shorthand Ajax funct ion which is equivalent to

        $ajax( url url dataType script success success)

        The callback is passed the returned JavaScript f ile This is generally not useful as the script willalready have run at this point

        The script is executed in the global context so it can refer to other variables and use jQueryfunct ions Included scripts can have some impact on the current page

        $(result)html(ltpgtLorem ipsum dolor sit ametltpgt)

        Scripts are included and run by referencing the f ile name

        $getScript(ajaxtestjs function(data textStatus) consolelog(data) data returned consolelog(textStatus) success consolelog(Load was performed))

        Note Should you require an addit ional callback for errors when using the getScript() methodthe global ajaxError() callback event may be used to achieve this as follows

        $( divlog )ajaxError(function(e jqxhr settings exception) if (settingsdataType==script) $(this)text( Triggered ajaxError handler ) )

        Example 1 Load the of f icial jQuery Color Animat ion plugin dynamically and bind some coloranimat ions to occur once the new funct ionality is loaded

        Javascript

        $getScript(httpdevjquerycomviewtrunkpluginscolorjquerycolorjs function() $(go)cl ick(function() $(block)animate( backgroundColor pink 1000) delay(500) animate( backgroundColor blue 1000) ))

        HTML

        ltbutton id=gogtampraquo Runltbuttongt

        ltdiv class=blockgtltdivgt

        CSS

        block background-color blue width 150px height 70px margin 10px

        jQuerygetJSON

        Load JSON-encoded data f rom the server using a GET HTTP request

        Added in version 10

        jQuerygetJSON(url data success(data textStatus jqXHR))jqXHR

        urlString A string containing the URL to which the request issent

        dataMap (opt ional) A map or string that is sent to the serverwith the request

        success(data textStatusjqXHR)Funct ion

        (opt ional) A callback funct ion that is executed if therequest succeeds

        This is a shorthand Ajax funct ion which is equivalent to

        $ajax( url url dataType json data data success callback)

        Data that is sent to the server is appended to the URL as a query string If the value of the dataparameter is an object (map) it is converted to a string and url-encoded before it is appendedto the URL

        Most implementat ions will specify a success handler

        $getJSON(ajaxtestjson function(data) var items = []

        $each(data function(key val) itemspush(ltli id= + key + gt + val + ltl igt) )

        $(ltulgt class my-new-list html itemsjoin( ) )appendTo(body))

        This example of course relies on the structure of the JSON f ile

        one Singular sensation two Beady l ittle 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 success callback is passed the returned data which is typically a JavaScript object or arrayas def ined by the JSON structure and parsed using the $parseJSON() method It is also passedthe text status of the response

        As of jQuery 15 the success callback funct ion receives a jqXHR object (in jQuery 14 itreceived the XMLHttpRequest object) However since JSONP and cross-domain GET requestsdo not use XHR in those cases the jqXHR and textStatus parameters passed to the successcallback are undef ined

        Important As of jQuery 14 if the JSON file contains a syntax error the requestwill usually fail silently Avoid frequent hand-editing of JSON data for this reasonJSON is a data-interchange format with syntax rules that are stricter than those ofJavaScripts object literal notation For example all strings represented in JSONwhether they are properties or values must be enclosed in double-quotes Fordetails on the JSON format see httpjsonorg

        JSONP

        If the URL includes the string callback= (or similar as def ined by the server-side API) therequest is t reated as JSONP instead See the discussion of the jsonp data type in $ajax() for

        more details

        The jqXHR Object

        As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $getJSON() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

        The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $getJSON()to chain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

        Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $getJSON(examplejson 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 abovejqxhrcomplete(function() alert(second complete) )

        Example 1 Loads the four most recent cat pictures f rom the Flickr JSONP API

        Javascript

        $getJSON(httpapifl ickrcomservicesfeedsphotos_publicgnejsoncallback= tags cat tagmode any format json function(data) $each(dataitems function(iitem) $(ltimggt)attr(src itemmediam)appendTo(images) i f ( i == 3 ) return false ) )

        HTML

        ltdiv id=imagesgt

        ltdivgt

        CSS

        img height 100px float left

        Example 2 Load the JSON data f rom test js and access a name from the returned JSON data

        Javascript

        $getJSON(testjs function(json) alert(JSON Data + jsonusers[3]name) )

        Example 3 Load the JSON data f rom test js passing along addit ional data and access a namefrom the returned JSON data

        Javascript

        $getJSON(testjs name John time 2pm function(json) alert(JSON Data + jsonusers[3]name) )

        jQueryget

        Load data f rom the server using a HTTP GET request

        Added in version 10

        jQueryget(url data success(data textStatus jqXHR) dataType)jqXHR

        urlString A string containing the URL to which the request is sent

        dataMap String (opt ional) A map or string that is sent to the server with therequest

        success(datatextStatusjqXHR)Funct ion

        (opt ional) A callback funct ion that is executed if the requestsucceeds

        dataTypeString (opt ional) The type of data expected from the server Default Intelligent Guess (xml json script or html)

        This is a shorthand Ajax funct ion which is equivalent to

        $ajax( url url data data success success dataType dataType)

        The success callback funct ion is passed the returned data which will be an XML root elementtext string JavaScript f ile or JSON object depending on the MIME type of the response It isalso passed the text status of the response

        As of jQuery 15 the success callback funct ion is also passed a jqXHR object (in jQuery 14 itwas passed the XMLHttpRequest object) However since JSONP and cross-domain GETrequests do not use XHR in those cases the (j)XHR and textStatus parameters passed to thesuccess callback are undef ined

        Most implementat ions will specify a success handler

        $get(ajaxtesthtml 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

        As of jQuery 15 all of jQuerys Ajax methods return a superset of the XMLHTTPRequestobject This jQuery XHR object or jqXHR returned by $get() implements the Promiseinterface giving it all the propert ies methods and behavior of a Promise (see Deferred objectfor more informat ion) For convenience and consistency with the callback names used by$ajax() it provides error() success() and complete() methods These methods take a funct ionargument that is called when the request terminates and the funct ion receives the samearguments as the correspondingly-named $ajax() callback

        The Promise interface in jQuery 15 also allows jQuerys Ajax methods including $get() tochain mult iple success() complete() and error() callbacks on a single request and even toassign these callbacks af ter the request may have completed If the request is alreadycomplete the callback is f ired immediately

        Assign handlers immediately after making the request and remember the jqxhr object for this request var jqxhr = $get(examplephp 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 jqxhrcomplete(function() alert(second complete) )

        Example 1 Request the test php page but ignore the return results

        Javascript

        $get(testphp)

        Example 2 Request the test php page and send some addit ional data along (while st ill ignoringthe return results)

        Javascript

        $get(testphp name John time 2pm )

        Example 3 pass arrays of data to the server (while st ill ignoring the return results)

        Javascript

        $get(testphp choices[] [ Jon Susan] )

        Example 4 Alert out the results f rom request ing test php (HTML or XML depending on whatwas returned)

        Javascript

        $get(testphp function(data)alert(Data Loaded + data))

        Example 5 Alert out the results f rom request ing test cgi with an addit ional payload of data

        (HTML or XML depending on what was returned)

        Javascript

        $get(testcgi name John time 2pm function(data) alert(Data Loaded + data) )

        Example 6 Gets the test php page contents which has been returned in json format(Johnt ime=gt2pm)) gt) and adds it to the page

        Javascript

        $get(testphp function(data) $(body)append( Name + dataname ) John append( Time + datatime ) 2pm json)

        load

        Load data f rom the server and place the returned HTML into the matched element

        Added in version 10

        load(url data complete(responseText textStatus XMLHttpRequest))jQuery

        urlString A string containing the URL to which therequest is sent

        dataMap String A map or string that is sent to the server withthe request

        complete(responseText textStatusXMLHttpRequest)Funct ion

        (opt ional) A callback funct ion that is executedwhen the request completes

        This method is the simplest way to fetch data f rom the server It is roughly equivalent to$get(url data success) except that it is a method rather than global funct ion and it has animplicit callback funct ion When a successful response is detected (ie when textStatus issuccess or notmodif ied) load() sets the HTML contents of the matched element to thereturned data This means that most uses of the method can be quite simple

        $(result)load(ajaxtesthtml)

        The provided callback if any is executed af ter this post-processing has been performed

        $(result)load(ajaxtesthtml function() alert(Load was performed))

        In the two examples above if the current document does not contain an element with an ID ofresult the load() method is not executed

        The POST method is used if data is provided as an object otherwise GET is assumed

        Note The event handling suite also has a method named load() Which one isfired depends on the set of arguments passed

        Loading Page Fragments

        The load() method unlike $get() allows us to specify a port ion of the remote document to beinserted This is achieved with a special syntax for the url parameter If one or more spacecharacters are included in the string the port ion of the string following the f irst space isassumed 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(ajaxtesthtml container)

        When this method executes it retrieves the content of ajaxtest html but then jQuery parsesthe returned document to f ind the element with an ID of container This element along with itscontents is inserted into the element with an ID of result and the rest of the retrieveddocument is discarded

        jQuery uses the browsers innerHTML property to parse the retrieved document and insert itinto the current document During this process browsers of ten f ilter elements f rom thedocument such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements retrieved byload() may not be exact ly the same as if the document were retrieved direct ly by the browser

        Example 1 Load the main pages footer navigat ion into an ordered list

        Javascript

        $(new-nav)load( jq-footerNavigation l i)

        CSS

        body font-size 12px font-family Arial

        HTML

        ltbgtFooter navigationltbgtltol id=new-navgtltolgt

        Example 2 Display a not ice if the Ajax request encounters an error

        Javascript

        $(success)load(not-herephp function(response status xhr) if (status == error) var msg = Sorry but there was an error $(error)html(msg + xhrstatus + + xhrstatusText) )

        CSS

        body font-size 12px font-family Arial

        HTML

        ltbgtSuccessful Response (should be blank)ltbgtltdiv id=successgtltdivgtltbgtError Responseltbgtltdiv id=errorgtltdivgt

        Example 3 Load the feedshtml f ile into the div with the ID of feeds

        Javascript

        $(feeds)load(feedshtml)

        Results

        ltdiv id=feedsgtltbgt45ltbgt feeds foundltdivgt

        Example 4 pass arrays of data to the server

        Javascript

        $(objectID)load(testphp choices[] [ Jon Susan] )

        Example 5 Same as above but will POST the addit ional parameters to the server and acallback that is executed when the server is f inished responding

        Javascript

        $(feeds)load(feedsphp limit 25 function()alert(The last 25 entries in the feed have been loaded))

        jQueryajax

        Perform an asynchronous HTTP (Ajax) request

        Added in version 10

        jQueryajax(sett ings)jqXHR

        sett ingsMap A set of keyvalue pairs that conf igure the Ajax request All set t ings areopt ional A default can be set for any opt ion with $ajaxSetup()

        The $ajax() funct ion underlies all Ajax requests sent by jQuery It is of ten unnecessary todirect ly call this funct ion as several higher-level alternat ives like $get() and load() are availableand are easier to use If less common opt ions are required though $ajax() can be used moref lexibly

        At its simplest the $ajax() funct ion can be called with no arguments

        $ajax()

        Note Default set t ings can be set globally by using the $ajaxSetup() funct ion

        This example using no opt ions loads the contents of the current page but does nothing withthe result To use the result we can implement one of the callback funct ions

        The jqXHR Object

        The jQuery XMLHttpRequest (jqXHR) object returned by $ajax() as of jQuery 15 is a supersetof the browsers nat ive XMLHttpRequest object For example it contains responseText andresponseXML propert ies as well as a getResponseHeader() method When the transport

        mechanism is something other than XMLHttpRequest (for example a script tag for a JSONPrequest) the jqXHR object simulates nat ive XHR funct ionality where possible

        As of jQuery 151 the jqXHR object also contains the overrideMimeType() method (it wasavailable in jQuery 14x as well but was temporarily removed in jQuery 15) TheoverrideMimeType() method may be used in the beforeSend() callback funct ion for exampleto modify the response content-type header

        $ajax( url httpfiddlejshellnetfaviconpng beforeSend function( xhr ) xhroverrideMimeType( textplain charset=x-user-defined ) success function( data ) i f (console ampamp consolelog) consolelog( Sample of data datasl ice(0100) ) )

        The jqXHR objects returned by $ajax() as of jQuery 15 implement the Promise interface givingthem all the propert ies methods and behavior of a Promise (see Deferred object for moreinformat ion) For convenience and consistency with the callback names used by $ajax() jqXHRalso provides error() success() and complete() methods These methods take a funct ionargument that is called when the $ajax() request terminates and the funct ion receives thesame arguments as the correspondingly-named $ajax() callback This allows you to assignmult iple callbacks on a single request and even to assign callbacks af ter the request may havecompleted (If the request is already complete the callback is f ired immediately)

        Deprecation Notice The jqXHRsuccess() jqXHRerror() and jqXHRcomplete()callbacks will be deprecated in jQuery 18 To prepare your code for their eventualremoval use jqXHRdone() jqXHRfail() and jqXHRalways() instead

        Assign handlers immediately after making the request and remember the jqxhr object for this requestvar jqxhr = $ajax( examplephp ) success(function() alert(success) ) error(function() alert(error) ) complete(function() alert(complete) )

        perform other work here

        Set another completion function for the request abovejqxhrcomplete(function() alert(second complete) )

        For backward compat ibility with XMLHttpRequest a jqXHR object will expose the followingpropert ies and methods

        readyState

        status

        statusText

        responseXML andor responseText when the underlying request responded with xmlandor text respect ively

        setRequestHeader(name value) which departs f rom the standard by replacing the oldvalue with the new one rather than concatenat ing the new value to the old one

        getAllResponseHeaders()

        getResponseHeader()

        abort()

        No onreadystatechange mechanism is provided however since success error complete andstatusCode cover all conceivable requirements

        Callback Function Queues

        The beforeSend error dataFilter success and complete opt ions all accept callback funct ionsthat are invoked at the appropriate t imes

        As of jQuery 15 the error (fail) success (done) and complete (always as of jQuery 16)callback hooks are f irst-in f irst-out managed queues This means you can assign more thanone callback for each hook See Deferred object methods which are implemented internally forthese $ajax() callback hooks

        The this reference within all callbacks is the object in the context opt ion passed to $ajax in thesett ings if context is not specif ied this is a reference to the Ajax sett ings themselves

        Some types of Ajax requests such as JSONP and cross-domain GET requests do not useXHR in those cases the XMLHttpRequest and textStatus parameters passed to the callbackare undef ined

        Here are the callback hooks provided by $ajax()

        1 beforeSend callback is invoked it receives the jqXHR object and the sett ings map asparameters

        2 error callbacks are invoked in the order they are registered if the request fails Theyreceive the jqXHR a string indicat ing the error type and an except ion object if applicableSome built -in errors will provide a string as the except ion object abort t imeout NoTransport

        3 dataFilter callback is invoked immediately upon successful receipt of response data Itreceives the returned data and the value of dataType and must return the (possiblyaltered) data to pass on to success

        4 success callbacks are then invoked in the order they are registered if the requestsucceeds They receive the returned data a string containing the success code and thejqXHR object

        5 complete callbacks f ire in the order they are registered when the request f inisheswhether in failure or success They receive the jqXHR object as well as a string containingthe success or error code

        For example to make use of the returned HTML we can implement a success handler

        $ajax( url ajaxtesthtml success function(data) $( result)html(data) alert(Load was performed) )

        Data Types

        The $ajax() funct ion relies on the server to provide informat ion about the retrieved data If theserver reports the return data as XML the result can be traversed using normal XML methodsor jQuerys selectors If another type is detected such as HTML in the example above the datais t reated as text

        Dif ferent data handling can be achieved by using the dataType opt ion Besides plain xml thedataType can be html json jsonp script or text

        The text and xml types return the data with no processing The data is simply passed on to thesuccess handler either through the responseText or responseXML property of the jqXHRobject respect ively

        Note We must ensure that the MIME type reported by the web server matches our choice ofdataType In part icular XML must be declared by the server as text xml or applicat ionxml forconsistent results

        If html is specif ied any embedded JavaScript inside the retrieved data is executed before theHTML is returned as a string Similarly script will execute the JavaScript that is pulled back fromthe server then return nothing

        The json type parses the fetched data f ile as a JavaScript object and returns the constructedobject as the result data To do so it uses jQueryparseJSON() when the browser supports it

        otherwise it uses a Funct ion constructor Malformed JSON data will throw a parse error (seejsonorg for more informat ion) JSON data is convenient for communicat ing structured data in away that is concise and easy for JavaScript to parse If the fetched data f ile exists on a remoteserver specify the jsonp type instead

        The jsonp type appends a query string parameter of callback= to the URL The server shouldprepend the JSON data with the callback name to form a valid JSONP response We canspecify a parameter name other than callback with the jsonp opt ion to $ajax()

        Note JSONP is an extension of the JSON format requiring some server-side code to detectand handle the query string parameter More informat ion about it can be found in the originalpost detailing its use

        When data is retrieved from remote servers (which is only possible using the script or jsonpdata types) the error callbacks and global events will never be f ired

        Sending Data to the Server

        By default Ajax requests are sent using the GET HTTP method If the POST method isrequired the method can be specif ied by sett ing a value for the type opt ion This opt ionaffects how the contents of the data opt ion are sent to the server POST data will always betransmit ted to the server using UTF-8 charset per the W3C XMLHTTPRequest standard

        The data opt ion can contain either a query string of the form key1=value1ampkey2=value2 or amap of the form key1 value1 key2 value2 If the lat ter form is used the data is convertedinto a query string using jQueryparam() before it is sent This processing can be circumventedby sett ing processData to false The processing might be undesirable if you wish to send anXML object to the server in this case change the contentType opt ion f rom applicat ionx-www-form-urlencoded to a more appropriate MIME type

        Advanced Options

        The global opt ion prevents handlers registered using ajaxSend() ajaxError() and similarmethods from f iring when this request would t rigger them This can be useful to for examplesuppress a loading indicator that was implemented with ajaxSend() if the requests are f requentand brief With cross-domain script and JSONP requests the global opt ion is automat ically setto false See the descript ions of these methods below for more details See the descript ions ofthese methods below for more details

        If the server performs HTTP authent icat ion before providing a response the user name andpassword pair can be sent via the username and password opt ions

        Ajax requests are t ime-limited so errors can be caught and handled to provide a better userexperience Request t imeouts are usually either lef t at their default or set as a global defaultusing $ajaxSetup() rather than being overridden for specif ic requests with the t imeout opt ion

        By default requests are always issued but the browser may serve results out of its cache Todisallow use of the cached results set cache to false To cause the request to report failure ifthe asset has not been modif ied since the last request set ifModif ied to t rue

        The scriptCharset allows the character set to be explicit ly specif ied for requests that use altscriptgt tag (that is a type of script or jsonp) This is useful if the script and host page havedif fering character sets

        The f irst let ter in Ajax stands for asynchronous meaning that the operat ion occurs in paralleland the order of complet ion is not guaranteed The async opt ion to $ajax() defaults to t rueindicat ing that code execut ion can cont inue af ter the request is made Sett ing this opt ion tofalse (and thus making the call no longer asynchronous) is strongly discouraged as it can causethe browser to become unresponsive

        The $ajax() funct ion returns the XMLHttpRequest object that it creates Normally jQueryhandles the creat ion of this object internally but a custom funct ion for manufacturing one canbe specif ied using the xhr opt ion The returned object can generally be discarded but doesprovide a lower-level interface for observing and manipulat ing the request In part icular callingabort() on the object will halt the request before it completes

        Extending Ajax

        As of jQuery 15 jQuerys Ajax implementat ion includes pref ilters converters and transportsthat allow you to extend Ajax with a great deal of f lexibility For more informat ion about theseadvanced features see the Extending Ajax page

        Example 1 Load and execute a JavaScript f ile

        Javascript

        $ajax( type GET url testjs dataType script )

        Example 2 Save some data to the server and not ify the user once it s complete

        Javascript

        $ajax( type POST url somephp data name=Johnamplocation=Boston success function(msg) alert( Data Saved + msg ) )

        Example 3 Retrieve the latest version of an HTML page

        Javascript

        $ajax( url testhtml cache false success function(html) $(results)append(html) )

        Example 4 Loads data synchronously Blocks the browser while the requests is act ive It isbetter to block user interact ion by other means when synchronizat ion is necessary

        Javascript

        var html = $ajax( url somephp async false )responseText

        Example 5 Sends an xml document as data to the server By sett ing the processData opt ion tofalse the automat ic conversion of data to strings is prevented

        Javascript

        var xmlDocument = [create xml document] $ajax( url pagephp processData false data xmlDocument success handleResponse )

        Example 6 Sends an id as data to the server save some data to the server and not ify the useronce it s complete Note that this usage - returning the result of the call into a variable -

        requires a synchronous (blocking) request (asyncfalse)

        Javascript

        var bodyContent = $ajax( url scriptphp global false type POST data id thisgetAttribute( id) dataType html asyncfalse success function(msg) alert(msg) )responseText

        jQueryparam see Forms

        Miscellaneous

        each see Traversing

        toArray

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

        Added in version 14

        toArray()Array

        toArray() returns all of the elements in the jQuery set

        alert($( l i )toArray())

        All of the matched DOM nodes are returned by this call contained in a standard array

        [ltli id=foogt ltli id=bargt]

        Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

        Javascript

        function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)toArray()reverse() )

        CSS

        span colorred

        HTML

        Reversed - ltspangtltspangt

        ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

        index

        Search for a given element f rom among the matched elements

        Added in version 10

        index(element)Number

        elementElementjQuery

        The DOM element or f irst element within the jQuery object tolook for

        Return Values

        If no argument is passed to the index() method the return value is an integer indicat ing theposit ion of the f irst element within the jQuery object relat ive to its sibling elements

        If index() is called on a collect ion of elements and a DOM element or jQuery object is passed inindex() returns an integer indicat ing the posit ion of the passed element relat ive to the originalcollect ion

        If a selector string is passed as an argument index() returns an integer indicat ing the posit ionof the original element relat ive to the elements matched by the selector If the element is notfound index() will return -1

        Detail

        The complementary operat ion to get() which accepts an index and returns a DOM nodeindex() can take a DOM node and returns an index Suppose we have a simple unordered list onthe page

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgt

        If we retrieve one of the three list items (for example through a DOM funct ion or as thecontext to an event handler) index() can search for this list item within the set of matchedelements

        var l istItem = documentgetElementById(bar)alert( Index + $( l i )index(l istItem))We get back the zero-based position of the l ist item

        Index 1

        Similarly if we retrieve a jQuery object consist ing of one of the three list items index() willsearch for that list item

        var l istItem = $(bar)alert( Index + $( l i )index(l istItem))

        We get back the zero-based posit ion of the list item

        Index 1

        Note that if the jQuery collect ion used as the index() methods argument contains more thanone element the f irst element within the matched set of elements will be used

        var l istItems = $( l i gt(0))alert( Index + $( l i )index(l istItems))

        We get back the zero-based posit ion of the f irst list item within the matched set

        Index 1

        If we use a string as the index() methods argument it is interpreted as a jQuery selector string

        The f irst element among the object s matched elements which also matches this selector islocated

        var l istItem = $(bar)alert( Index + l istItemindex( l i ))

        We get back the zero-based posit ion of the list item

        Index 1

        If we omit the argument index() will return the posit ion of the f irst element within the set ofmatched elements in relat ion to its siblings

        alert( Index + $(bar)index()

        Again we get back the zero-based posit ion of the list item

        Index 1

        Example 1 On click returns the index (based zero) of that div in the page

        Javascript

        $(div)cl ick(function () this is the dom element cl icked var index = $(div)index(this) $(span)text(That was div index + index))

        CSS

        div backgroundyellow margin5px span colorred

        HTML

        ltspangtClick a divltspangtltdivgtFirst divltdivgtltdivgtSecond divltdivgtltdivgtThird divltdivgt

        Example 2 Returns the index for the element with ID bar

        CSS

        div font-weight bold color 090

        Javascript

        var l istItem = $(bar) $(div)html( Index + $( l i )index(l istItem) )

        HTML

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

        Example 3 Returns the index for the f irst item in the jQuery collect ion

        CSS

        div font-weight bold color 090

        Javascript

        var l istItems = $( l i gt(0))$(div)html( Index + $( l i )index(l istItems) )

        HTML

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

        Example 4 Returns the index for the element with ID bar in relat ion to all

        elements

        CSS

        div font-weight bold color 090

        Javascript

        $(div)html( Index + $(bar)index( l i ) )

        HTML

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

        Example 5 Returns the index for the element with ID bar in relat ion to its siblings

        CSS

        div font-weight bold color 090

        Javascript

        var barIndex = $(bar)index()$(div)html( Index + barIndex )

        HTML

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

        Example 6 Returns -1 as there is no element with ID foobar

        CSS

        div font-weight bold color 090

        Javascript

        var foobar = $(l i)index( $(foobar) )$(div)html( Index + foobar)

        HTML

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligt ltli id=bazgtbazltligtltulgtltdivgtltdivgt

        removeData see Data

        data see Data

        data see Data

        get

        Retrieve the DOM elements matched by the jQuery object

        Added in version 10

        get(index)Element Array

        indexNumber (opt ional) A zero-based integer indicat ing which element to retrieve

        The get() method grants us access to the DOM nodes underlying each jQuery object Supposewe had a simple unordered list on the page

        ltulgt ltli id=foogtfooltligt ltli id=bargtbarltligtltulgt

        Without a parameter get() returns all of the elements

        alert($( l i )get())

        All of the matched DOM nodes are returned by this call contained in a standard array

        [ltli id=foogt ltli id=bargt]

        With an index specif ied get() will retrieve a single element

        ($( l i )get(0))

        Since the index is zero-based the f irst list item is returned

        ltli id=foogt

        Each jQuery object also masquerades as an array so we can use the array dereferencingoperator to get at the list item instead

        alert($( l i )[0])

        However this syntax lacks some of the addit ional capabilit ies of get() such as specifying anegat ive index

        alert($( l i )get(-1))

        A negat ive index is counted from the end of the matched set so this example will return thelast item in the list

        ltli id=bargt

        Example 1 Selects all divs in the document and returns the DOM Elements as an Array thenuses the built -in reverse-method to reverse that array

        Javascript

        function disp(divs) var a = [] for (var i = 0 i lt divslength i++) apush(divs[i]innerHTML) $(span)text(ajoin( )) disp( $(div)get()reverse() )

        CSS

        span colorred

        HTML

        Reversed - ltspangtltspangt

        ltdivgtOneltdivgt ltdivgtTwoltdivgt ltdivgtThreeltdivgt

        Example 2 Gives the tag name of the element clicked on

        Javascript

        $( documentbody)cl ick(function (e) estopPropagation() var domEl = $(this)get(0) $(spanfirst)text(Clicked on - + domEltagName) )

        CSS

        span colorred div backgroundyellow

        HTML

        ltspangtampnbspltspangt ltpgtIn this paragraph is an ltspangtimportantltspangt sectionltpgt

        ltdivgtltinput type=text gtltdivgt

        size

        Return the number of elements in the jQuery object

        Added in version 10

        size()Number

        The size() method is funct ionally equivalent to the length property however the lengthproperty is preferred because it does not have the overhead of a funct ion call

        Given a simple unordered list on the page

        ltulgt ltligtfooltligt ltligtbarltligtltulgt

        Both size() and length ident ify the number of items

        alert( Size + $(l i)size() )alert( Size + $(l i)length )

        This results in two alerts

        Size 2

        Size 2

        Example 1 Count the divs Click to add more

        Javascript

        $(documentbody)cl ick(function() $(this)append( $(ltdivgt) ) var n = $(div)size() $(span)text(There are + n + divs Click to add more)) trigger the cl ick to startcl ick()

        CSS

        body cursorpointer min-height 100px div width50px height30px margin5px floatleft backgroundblue span colorred

        HTML

        ltspangtltspangt ltdivgtltdivgt

        jQuerynoConflict see Core

        jQueryparam see Forms

        Dimensions

        outerWidth see CSS

        outerHeight see CSS

        innerWidth see CSS

        innerHeight see CSS

        width see CSS

        width see CSS

        height see CSS

        height see CSS

        Offset

        offsetParent see Traversing

        scrollLeft see CSS

        scrollLeft see CSS

        scrollTop see CSS

        scrollTop see CSS

        position see CSS

        offset see CSS

        offset see CSS

        Utilities

        jQuerynow

        Return a number represent ing the current t ime

        Added in version 143

        jQuerynow()Number

        The $now() method is a shorthand for the number returned by the expression (newDate)getTime()

        jQueryparseXML

        Parses a string into an XML document

        Added in version 15

        jQueryparseXML(data)XMLDocument

        dataString a well-formed XML string to be parsed

        jQueryparseXML uses the nat ive parsing funct ion of the browser to create a valid XMLDocument This document can then be passed to jQuery to create a typical jQuery object thatcan be traversed and manipulated

        Example 1 Create a jQuery object using an XML string and obtain the value of the t it le node

        HTML

        ltp id=someElementgtltpgtltp id=anotherElementgtltpgt

        Javascript

        var xml = ltrss version=20gtltchannelgtlttitlegtRSS Titlelttitlegtltchannelgtltrssgt xmlDoc = $parseXML( xml ) $xml = $( xmlDoc ) $title = $xmlfind( title )

        append RSS Title to someElement $( someElement )append( $titletext() )

        change the title to XML Title $titletext( XML Title )

        append XML Title to anotherElement $( anotherElement )append( $titletext() )

        jQuerytype

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

        Added in version 143

        jQuerytype(obj)String

        objObject 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

        If the object is undef ined or null then undef ined or null is returned accordingly

        If the object has an internal [[Class]] equivalent to one of the browsers built -in objectsthe associated name is returned (More details about this technique)

        jQuerytype(true) === boolean

        jQuerytype(3) === number

        jQuerytype(test) === string

        jQuerytype(funct ion()) === funct ion

        jQuerytype([]) === array

        jQuerytype(new Date()) === date

        jQuerytype(test ) === regexp

        Everything else returns object as its type

        Example 1 Find out if the parameter is a RegExp

        Javascript

        $(b)append( + jQuerytype(test) )

        HTML

        Is it a RegExp ltbgtltbgt

        jQueryisWindow

        Determine whether the argument is a window

        Added in version 143

        jQueryisWindow(obj)boolean

        objObject Object to test whether or not it is a window

        This is used in a number of places in jQuery to determine if were operat ing against a browserwindow (such as the current window or an if rame)

        Example 1 Finds out if the parameter is a window

        Javascript

        $(b)append( + $isWindow(window) )

        HTML

        Is window a window ltbgtltbgt

        jQueryparseJSON

        Takes a well-formed JSON string and returns the result ing JavaScript object

        Added in version 141

        jQueryparseJSON(json)Object

        jsonString The JSON string to parse

        Passing in a malformed JSON string may result in an except ion being thrown For example thefollowing are all malformed JSON strings

        test 1 (test does not have double quotes around it )

        test 1 (test is using single quotes instead of double quotes)

        Addit ionally if you pass in nothing an empty string null or undef ined null will be returned fromparseJSON Where the browser provides a nat ive implementat ion of JSONparse jQuery uses itto parse the string For details on the JSON format see ht tpjsonorg

        Example 1 Parse a JSON string

        Javascript

        var obj = jQueryparseJSON(nameJohn)alert( objname === John )

        jQueryproxy see Events

        jQuerycontains

        Check to see if a DOM element is within another DOM element

        Added in version 14

        jQuerycontains(container contained)Boolean

        containerElement The DOM element that may contain the other element

        containedElement The DOM element that may be contained by the other element

        Example 1 Check if an element is inside another Text and comment nodes are not supported

        Javascript

        jQuerycontains(documentdocumentElement documentbody) truejQuerycontains(documentbody documentdocumentElement) false

        jQuerynoop

        An empty funct ion

        Added in version 14

        jQuerynoop()Funct ion

        You can use this empty funct ion when you wish to pass around a funct ion that will do nothing

        This is useful for plugin authors who of fer opt ional callbacks in the case that no callback isgiven something like jQuerynoop could execute

        jQueryglobalEval

        Execute some JavaScript code globally

        Added in version 104

        jQueryglobalEval(code)

        codeString The JavaScript code to execute

        This method behaves dif ferent ly f rom using a normal JavaScript eval() in that it s executedwithin the global context (which is important for loading external scripts dynamically)

        Example 1 Execute a script in the global context

        Javascript

        function test() jQueryglobalEval(var newVar = true)test() newVar === true

        jQueryisXMLDoc

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

        Added in version 114

        jQueryisXMLDoc(node)Boolean

        nodeElement The DOM node that will be checked to see if it s in an XML document

        Example 1 Check an object to see if it s in an XML document

        Javascript

        jQueryisXMLDoc(document) falsejQueryisXMLDoc(documentbody) false

        jQueryremoveData see Data

        jQuerydata see Data

        jQuerydata see Data

        jQuerydequeue see Data

        jQueryqueue see Data

        jQueryqueue see Data

        clearQueue see Data

        jQueryisEmptyObject

        Check to see if an object is empty (contains no propert ies)

        Added in version 14

        jQueryisEmptyObject(object)Boolean

        object Object The object that will be checked to see if it s empty

        As of jQuery 14 this method checks both propert ies on the object itself and propert iesinherited f rom prototypes (in that it doesnt use hasOwnProperty) The argument shouldalways be a plain JavaScript Object as other types of object (DOM elements primit ivestringsnumbers host objects) may not give consistent results across browsers To determine ifan object is a plain JavaScript object use $isPlainObject()

        Example 1 Check an object to see if it s empty

        Javascript

        jQueryisEmptyObject() truejQueryisEmptyObject( foo bar ) false

        jQueryisPlainObject

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

        Added in version 14

        jQueryisPlainObject(object)Boolean

        object Object The object that will be checked to see if it s a plain object

        Note Host objects (or objects used by browser host environments to complete the execut ionenvironment of ECMAScript) have a number of inconsistencies which are dif f icult to robust lyfeature detect cross-plat form As a result of this $isPlainObject() may evaluate inconsistent lyacross browsers in certain instances

        An example of this is a test against documentlocat ion using $isPlainObject() as follows

        consolelog($isPlainObject(documentlocation))

        which throws an invalid pointer except ion in IE8 With this in mind it s important to be aware ofany of the gotchas involved in using $isPlainObject() against older browsers Some basicexample of use-cases that do funct ion correct ly cross-browser can be found below

        Example 1 Check an object to see if it s a plain object

        Javascript

        jQueryisPlainObject() truejQueryisPlainObject(test) false

        dequeue see Data

        queue see Data

        queue see Data

        jQuerybrowser

        Contains f lags for the useragent read from navigatoruserAgent We recommend against usingthis property please try to use feature detect ion instead (see jQuerysupport) jQuerybrowsermay be moved to a plugin in a future release of jQuery

        Added in version 10

        The $browser property provides informat ion about the web browser that is accessing thepage as reported by the browser itself It contains f lags for each of the four most prevalentbrowser classes (Internet Explorer Mozilla Webkit and Opera) as well as version informat ion

        Available f lags are

        webkit (as of jQuery 14)

        safari (deprecated)

        opera

        msie

        mozilla

        This property is available immediately It is therefore safe to use it to determine whether or notto call $(document)ready() The $browser property is deprecated in jQuery 13 and itsfunct ionality may be moved to a team-supported plugin in a future release of jQuery

        Because $browser uses navigatoruserAgent to determine the plat form it is vulnerable tospoof ing by the user or misrepresentat ion by the browser itself It is always best to avoidbrowser-specif ic code ent irely where possible The $support property is available for detect ionof support for part icular features rather than relying on $browser

        Example 1 Show the browser info

        Javascript

        jQueryeach(jQuerybrowser function(i val) $(ltdivgt + i + ltspangt + val + ltspangt) appendTo( documentbody ) )

        CSS

        p colorgreen font-weightbolder margin3px 0 0 10px div colorblue margin-left20px font-size14px span colorred

        HTML

        ltpgtBrowser infoltpgt

        Example 2 Returns t rue if the current useragent is some version of Microsoft s InternetExplorer

        Javascript

        $browsermsie

        Example 3 Alerts this is WebKit only for WebKit browsers

        Javascript

        i f ($browserwebkit) alert( this is webkit )

        Example 4 Alerts Do stuf f for Firefox 3 only for Firefox 3 browsers

        Javascript

        var ua = $browser i f ( uamozil la ampamp uaversionsl ice(03) == 19 ) alert( Do stuff for firefox 3 )

        Example 5 Set a CSS property that s specif ic to a part icular browser

        Javascript

        i f ( $browsermsie ) $(div ul l i)css( display inl ine ) else $(div ul l i)css( display inl ine-table )

        jQuerybrowserversion

        The version number of the rendering engine for the users browser

        Added in version 113

        Here are some typical results

        Internet Explorer 60 70 80

        MozillaFirefoxFlockCamino 1712 1813 19

        Opera 1006 1101

        SafariWebkit 3128 4189

        Note that IE8 claims to be 7 in Compat ibility View

        Example 1 Returns the version number of the rendering engine used by the users currentbrowser For example FireFox 4 returns 20 (the version of the Gecko rendering engine itut ilizes)

        Javascript

        $(p)html( The version number of the rendering engine your browser uses is ltspangt + $browserversion + ltspangt )

        CSS

        p colorblue margin20px span colorred

        HTML

        ltpgtltpgt

        Example 2 Alerts the version of IEs rendering engine that is being used

        Javascript

        i f ( $browsermsie ) alert( $browserversion )

        Example 3 Often you only care about the major number the whole number which you canget by using JavaScript s built -in parseInt() funct ion

        Javascript

        i f ( $browsermsie ) alert( parseInt($browserversion 10) )

        jQuerytrim

        Remove the whitespace from the beginning and end of a string

        Added in version 10

        jQueryt rim(str)String

        strString The string to t rim

        The $t rim() funct ion removes all newlines spaces (including non-breaking spaces) and tabsfrom the beginning and end of the supplied string If these whitespace characters occur in themiddle of the string they are preserved

        Example 1 Remove the two white spaces at the start and at the end of the string

        Javascript

        $(button)cl ick(function () var str = lots of spaces before and after alert( + str + )

        str = jQuerytrim(str)alert( + str + - no longer))

        HTML

        ltbuttongtShow Trim Exampleltbuttongt

        Example 2 Remove the two white spaces at the start and at the end of the string

        Javascript

        $trim( hello how are you )

        Results

        hello how are you

        jQueryisFunction

        Determine if the argument passed is a Javascript funct ion object

        Added in version 12

        jQueryisFunct ion(obj)boolean

        objObject Object to test whether or not it is a funct ion

        Note As of jQuery 13 funct ions provided by the browser like alert() and DOM elementmethods like getAttribute() are not guaranteed to be detected as funct ions in browsers suchas Internet Explorer

        Example 1 Test a few parameter examples

        Javascript

        function stub() var objs = [ function () x15 y20 null stub function ]

        jQueryeach(objs function (i) var isFunc = jQueryisFunction(objs[i]) $(span)eq(i)text(isFunc) )

        CSS

        div colorblue margin2px font-size14px span colorred

        HTML

        ltdivgtjQueryisFunction(objs[0]) = ltspangtltspangtltdivgt

        ltdivgtjQueryisFunction(objs[1]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[2]) = ltspangtltspangtltdivgt ltdivgtjQueryisFunction(objs[3]) = ltspangtltspangtltdivgt

        ltdivgtjQueryisFunction(objs[4]) = ltspangtltspangtltdivgt

        Example 2 Finds out if the parameter is a funct ion

        Javascript

        $isFunction(function())

        Results

        true

        jQueryisArray

        Determine whether the argument is an array

        Added in version 13

        jQueryisArray(obj)boolean

        objObject Object to test whether or not it is an array

        $isArray() returns a Boolean indicat ing whether the object is a JavaScript array (not an array-like object such as a jQuery object)

        Example 1 Finds out if the parameter is an array

        Javascript

        $(b)append( + $isArray([]) )

        HTML

        Is [] an Array ltbgtltbgt

        jQueryunique

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

        Added in version 113

        jQueryunique(array)Array

        arrayArray The Array of DOM elements

        The $unique() funct ion searches through an array of objects sort ing the array and removingany duplicate nodes This funct ion only works on plain JavaScript arrays of DOM elements andis chief ly used internally by jQuery

        As of jQuery 14 the results will always be returned in document order

        Example 1 Removes any duplicate elements f rom the array of divs

        Javascript

        var divs = $(div)get() unique() must take a native array

        add 3 elements of class dup too (they are divs) divs = divsconcat($(dup)get()) $(diveq(1))text(Pre-unique there are + divslength + elements)

        divs = jQueryunique(divs) $(diveq(2))text(Post-unique there are + divslength + elements) css(color red)

        CSS

        div colorblue

        HTML

        ltdivgtThere are 6 divs in this documentltdivgt ltdivgtltdivgt ltdiv class=dupgtltdivgt ltdiv class=dupgtltdivgt

        ltdiv class=dupgtltdivgt ltdivgtltdivgt

        jQuerymerge

        Merge the contents of two arrays together into the f irst array

        Added in version 10

        jQuerymerge(f irst second)Array

        f irst Array The f irst array to merge the elements of second added

        secondArray The second array to merge into the f irst unaltered

        The $merge() operat ion forms an array that contains all elements f rom the two arrays Theorders of items in the arrays are preserved with items from the second array appended The$merge() funct ion is destruct ive It alters the f irst parameter to add the items from the second

        If you need the original f irst array make a copy of it before calling $merge() Fortunately$merge() itself can be used for this duplicat ion

        var newArray = $merge([] oldArray)

        This shortcut creates a new empty array and merges the contents of oldArray into it ef fect ively cloning the array

        Prior to jQuery 14 the arguments should be true Javascript Array objects use $makeArray ifthey are not

        Example 1 Merges two arrays altering the f irst argument

        Javascript

        $merge( [012] [234] )

        Results

        [012234]

        Example 2 Merges two arrays altering the f irst argument

        Javascript

        $merge( [321] [432] )

        Results

        [321432]

        Example 3 Merges two arrays but uses a copy so the original isnt altered

        Javascript

        var first = [abc]var second = [de f]$merge( $merge([]first) second)

        Results

        [abcdef]

        jQueryinArray

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

        Added in version 12

        jQueryinArray(value array)Number

        valueAny The value to search for

        arrayArray An array through which to search

        The $inArray() method is similar to JavaScript s nat ive indexOf() method in that it returns -1when it doesnt f ind a match If the f irst element within the array matches value $inArray()returns 0

        Because JavaScript t reats 0 as loosely equal to false (ie 0 == false but 0 == false) if werechecking for the presence of value within array we need to check if it s not equal to (or greaterthan) -1

        Example 1 Report the index of some elements in the array

        Javascript

        var arr = [ 4 Pete 8 John ]

        $(spaneq(0))text(jQueryinArray(John arr))$(spaneq(1))text(jQueryinArray(4 arr))$(spaneq(2))text(jQueryinArray(Karl arr))

        CSS

        div colorblue span colorred

        HTML

        ltdivgtJohn found at ltspangtltspangtltdivgtltdivgt4 found at ltspangtltspangtltdivgtltdivgtKarl not found so ltspangtltspangtltdivgt

        jQuerymap

        Translate all items in an array or object to new array of items

        Added in version 16

        jQuerymap(arrayOrObject callback( value indexOrKey ))Array

        arrayOrObject ArrayObject The Array or Object to t ranslate

        callback( value indexOrKey)Funct ion

        The funct ion to process each item against The f irstargument to the funct ion is the value the secondargument is the index or key of the array or objectproperty The funct ion can return any value to add to thearray A returned array will be f lat tened into the result ingarray Within the funct ion this refers to the global (window)object

        The $map() method applies a funct ion to each item in an array or object and maps the resultsinto a new array Prior to jQuery 16 $map() supports t raversing arrays only As of jQuery 16 italso t raverses objects

        Array-like objects acirceurordquo those with a length property and a value on the length - 1 index acirceurordquo mustbe converted to actual arrays before being passed to $map() The jQuery library provides$makeArray() for such conversions

        The following object masquerades as an arrayvar fakeArray = length 1 0 Addy 1 Subtracty

        Therefore convert it to a real arrayvar realArray = $makeArray( fakeArray )

        Now it can be used reliably with $map()$map( realArray function(val i) do something )

        The translat ion funct ion that is provided to this method is called for each top-level element inthe array or object and is passed two arguments The element s value and its index or keywithin the array or object

        The funct ion can return

        the translated value which will be mapped to the result ing array

        null to remove the item

        an array of values which will be f lat tened into the full array

        Example 1 A couple examples of using map()

        Javascript

        var arr = [ a b c d e ] $(div)text(arrjoin( ))

        arr = jQuerymap(arr function(n i) return (ntoUpperCase() + i) ) $(p)text(arrjoin( ))

        arr = jQuerymap(arr function (a) return a + a ) $(span)text(arrjoin( ))

        CSS

        div colorblue p colorgreen margin0 span colorred

        HTML

        ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

        Example 2 Map the original array to a new one and add 4 to each value

        Javascript

        $map( [012] function(n) return n + 4 )

        Results

        [4 5 6]

        Example 3 Maps the original array to a new one and adds 1 to each value if it is bigger thenzero otherwise it s removed

        Javascript

        $map( [012] function(n) return n gt 0 n + 1 null )

        Results

        [2 3]

        Example 4 Map the original array to a new one each element is added with its original valueand the value plus one

        Javascript

        $map( [012] function(n) return [ n n + 1 ] )

        Results

        [0 1 1 2 2 3]

        Example 5 Map the original object to a new array and double each value

        Javascript

        var dimensions = width 10 height 15 length 20 dimensions = $map( dimensions function( value index ) return value 2)

        Results

        [20 30 40]

        Example 6 Map an object s keys to an array

        Javascript

        var dimensions = width 10 height 15 length 20 keys = $map( dimensions function( value index ) return index )

        Results

        [width height length]

        Example 7 Maps the original array to a new one each element is squared

        Javascript

        $map( [0123] function (a) return a a )

        Results

        [0 1 4 9]

        Example 8 Remove items by returning null f rom the funct ion This removes any numbers lessthan 50 and the rest are decreased by 45

        Javascript

        $map( [0 1 52 97] function (a) return (a gt 50 a - 45 null) )

        Results

        [7 52]

        Example 9 Augment ing the result ing array by returning an array inside the funct ion

        Javascript

        var array = [0 1 52 97]array = $map(array function(a index) return [a - 45 index])

        Results

        [-45 0 -44 1 7 2 52 3]

        jQuerymakeArray

        Convert an array-like object into a t rue JavaScript array

        Added in version 12

        jQuerymakeArray(obj)Array

        objObject Any object to turn into a nat ive Array

        Many methods both in jQuery and in JavaScript in general return objects that are array-like Forexample the jQuery factory funct ion $() returns a jQuery object that has many of thepropert ies of an array (a length the [] array access operator etc) but is not exact ly the sameas an array and lacks some of an arrays built -in methods (such as pop() and reverse())

        Note that af ter the conversion any special features the object had (such as the jQuerymethods in our example) will no longer be present The object is now a plain array

        Example 1 Turn a collect ion of HTMLElements into an Array of them

        Javascript

        var elems = documentgetElementsByTagName(div) returns a nodeList var arr = jQuerymakeArray(elems) arrreverse() use an Array method on l ist of dom elements $(arr)appendTo(documentbody)

        CSS

        div colorred

        HTML

        ltdivgtFirstltdivgt ltdivgtSecondltdivgt ltdivgtThirdltdivgt

        ltdivgtFourthltdivgt

        Example 2 Turn a jQuery object into an array

        Javascript

        var obj = $( l i ) var arr = $makeArray(obj)

        Results

        (typeof obj === object ampamp objjquery) === truejQueryisArray(arr) === true

        jQuerygrep

        Finds the elements of an array which sat isfy a f ilter funct ion The original array is not af fected

        Added in version 10

        jQuerygrep(array funct ion(elementOfArray indexInArray) invert)Array

        arrayArray The array to search through

        funct ion(elementOfArrayindexInArray)Funct ion

        The funct ion to process each item against The f irstargument to the funct ion is the item and the secondargument is the index The funct ion should return a Booleanvalue this will be the global window object

        invert Boolean (opt ional) If invert is false or not provided then thefunct ion returns an array consist ing of all elements for whichcallback returns t rue If invert is t rue then the funct ionreturns an array consist ing of all elements for whichcallback returns false

        The $grep() method removes items from an array as necessary so that all remaining items passa provided test The test is a funct ion that is passed an array item and the index of the itemwithin the array Only if the test returns t rue will the item be in the result array

        The f ilter funct ion will be passed two arguments the current array item and its index The f ilterfunct ion must return t rue to include the item in the result array

        Example 1 Filters the original array of numbers leaving that are not 5 and have an index greaterthan 4 Then it removes all 9s

        Javascript

        var arr = [ 1 9 3 8 6 1 5 9 4 7 3 8 6 9 1 ]$(div)text(arrjoin( ))

        arr = jQuerygrep(arr function(n i) return (n = 5 ampamp i gt 4))$(p)text(arrjoin( ))

        arr = jQuerygrep(arr function (a) return a = 9 )$(span)text(arrjoin( ))

        CSS

        div colorblue p colorgreen margin0 span colorred

        HTML

        ltdivgtltdivgt ltpgtltpgt ltspangtltspangt

        Example 2 Filter an array of numbers to include only numbers bigger then zero

        Javascript

        $grep( [012] function(ni) return n gt 0 )

        Results

        [1 2]

        Example 3 Filter an array of numbers to include numbers that are not bigger than zero

        Javascript

        $grep( [012] function(ni) return n gt 0true)

        Results

        [0]

        jQueryextend

        Merge the contents of two or more objects together into the f irst object

        Added in version 114

        jQueryextend(deep target object1 objectN)Object

        deepBoolean (opt ional) If t rue the merge becomes recursive (aka deep copy)

        targetObject The object to extend It will receive the new propert ies

        object1Object An object containing addit ional propert ies to merge in

        objectNObject (opt ional) Addit ional objects containing propert ies to merge in

        When we supply two or more objects to $extend() propert ies f rom all of the objects are addedto the target object

        If only one argument is supplied to $extend() this means the target argument was omit ted Inthis case the jQuery object itself is assumed to be the target By doing this we can add newfunct ions to the jQuery namespace This can be useful for plugin authors wishing to add newmethods to JQuery

        Keep in mind that the target object (f irst argument) will be modif ied and will also be returnedfrom $extend() If however we want to preserve both of the original objects we can do so bypassing an empty object as the target

        var object = $extend( object1 object2)

        The merge performed by $extend() is not recursive by default if a property of the f irst object isitself an object or array it will be completely overwrit ten by a property with the same key in thesecond object The values are not merged This can be seen in the example below by examiningthe value of banana However by passing true for the f irst funct ion argument objects will berecursively merged

        Undef ined propert ies are not copied However propert ies inherited f rom the object s prototypewill be copied over For performance reasons propert ies that have values of built -in JavaScripttypes such as Date or RegExp are not re-constructed and will appear as plain Objects in theresult ing object or array

        Note When performing a deep extend Object and Array are extended howeverprimitive types such string boolean and number are not For specific needs thatfall outside of this behaviour it is recommended to write a custom extend methodas this will be significantly faster from a performance perspective

        Example 1 Merge two objects modifying the f irst

        Javascript

        var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

        merge object2 into object1 $extend(object1 object2)

        var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

        $(log)append( printObj(object1) )

        HTML

        ltdiv id=loggtltdivgt

        Example 2 Merge two objects recursively modifying the f irst

        Javascript

        var object1 = apple 0 banana weight 52 price 100 cherry 97var object2 = banana price 200 durian 100

        merge object2 into object1 recursively $extend(true object1 object2)

        var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

        $(log)append( printObj(object1) )

        HTML

        ltdiv id=loggtltdivgt

        Example 3 Merge defaults and opt ions without modifying the defaults This is a commonplugin development pattern

        Javascript

        var defaults = validate false l imit 5 name foo var options = validate true name bar

        merge defaults and options without modifying defaults var settings = $extend( defaults options)

        var printObj = function(obj) var arr = [] $each(obj function(key val) var next = key + next += $isPlainObject(val) printObj(val) val arrpush( next ) ) return + arrjoin( ) +

        $(log)append( ltdivgtltbgtsettings -- ltbgt + printObj(settings) + ltdivgt )$(log)append( ltdivgtltbgtoptions -- ltbgt + printObj(options) + ltdivgt )

        HTML

        ltdiv id=loggtltdivgt

        jQueryeach

        A generic iterator funct ion which can be used to seamlessly iterate over both objects andarrays Arrays and array-like objects with a length property (such as a funct ions argumentsobject) are iterated by numeric index f rom 0 to length-1 Other objects are iterated via theirnamed propert ies

        Added in version 10

        jQueryeach(collect ion callback(indexInArray valueOfElement))Object

        collect ionObject The object or array to iterate over

        callback(indexInArrayvalueOfElement)Funct ion

        The funct ion that will be executed on everyobject

        The $each() funct ion is not the same as $(selector)each() which is used to iterate exclusivelyover a jQuery object The $each() funct ion can be used to iterate over any collect ion whetherit is a map (JavaScript object) or an array In the case of an array the callback is passed an arrayindex and a corresponding array value each t ime (The value can also be accessed through the

        this keyword but Javascript will always wrap the this value as an Object even if it is a simplestring or number value) The method returns its f irst argument the object that was iterated

        $each([52 97] function(index value) alert(index + + value) )

        This produces two messages

        0 52

        1 97

        If a map is used as the collect ion the callback is passed a key-value pair each t ime

        var map = flammable inflammable duh no duh $each(map function(key value) alert(key + + value) )

        Once again this produces two messages

        f lammable inf lammable

        duh no duh

        We can break the $each() loop at a part icular iterat ion by making the callback funct ion returnfalse Returning non-false is the same as a cont inue statement in a for loop it will skipimmediately to the next iterat ion

        Example 1 Iterates through the array displaying each number as both a word and numeral

        Javascript

        var arr = [ one two three four five ] var obj = one1 two2 three3 four4 five5

        jQueryeach(arr function() $( + this)text(Mine is + this + ) return (this = three) wil l stop running after three )

        jQueryeach(obj function(i val) $( + i)append(documentcreateTextNode( - + val)) )

        CSS

        div colorblue divfive colorred

        HTML

        ltdiv id=onegtltdivgt ltdiv id=twogtltdivgt ltdiv id=threegtltdivgt ltdiv id=fourgtltdivgt ltdiv id=fivegtltdivgt

        Example 2 Iterates over items in an array accessing both the current item and its index

        Javascript

        $each( [abc] function(i l) alert( Index + i + + l ) )

        Example 3 Iterates over the propert ies in an object accessing both the current item and its key

        Javascript

        $each( name John lang JS function(k v) alert( Key + k + Value + v ) )

        jQueryboxModel

        Deprecated in jQuery 13 (see jQuerysupport) States if the current page in the users browseris being rendered using the W3C CSS Box Model

        Added in version 10

        Example 1 Returns the box model for the if rame

        Javascript

        $(p)html(The box model for this iframe is ltspangt + jQueryboxModel + ltspangt)

        CSS

        p colorblue margin20px span colorred

        HTML

        ltpgt ltpgt

        Example 2 Returns false if the page is in Quirks Mode in Internet Explorer

        Javascript

        $boxModel

        Results

        false

        jQuerysupport

        A collect ion of propert ies that represent the presence of dif ferent browser features or bugs

        Added in version 13

        Rather than using $browser to detect the current user agent and alter the page presentat ionbased on which browser is running it is a good pract ice to perform feature detect ion Thismeans that prior to execut ing code which relies on a browser feature we test to ensure thatthe feature works properly To make this process simpler jQuery performs many such tests andmakes the results available to us as propert ies of the jQuerysupport object

        The values of all the support propert ies are determined using feature detect ion (and do notuse any form of browser snif f ing)

        Following are a few resources that explain how feature detection works

        httppetermichauxcaarticlesfeature-detection-state-of-the-art-browser-scripting

        httpwwwjibberingcomfaqfaq_notesnot_browser_detecthtml

        httpyurathinkweb2comcft

        While jQuery includes a number of propert ies developers should feel f ree to add their own as

        While jQuery includes a number of propert ies developers should feel f ree to add their own astheir needs dictate Many of the jQuerysupport propert ies are rather low-level so they aremost useful for plugin and jQuery core development rather than general day-to-daydevelopment Since jQuery requires these tests internally they must be performed on everypage load for that reason this list is kept short and limited to features needed by jQuery itself

        The tests included in jQuerysupport are as follows

        ajax is equal to t rue if a browser is able to create an XMLHttpRequest object

        boxModel is equal to t rue if the page is rendering according to the W3C CSS Box Model(is current ly false in IE 6 and 7 when they are in Quirks Mode) This property is null unt ildocument ready occurs

        changeBubbles is equal to t rue if the change event bubbles up the DOM tree asrequired by the W3C DOM event model (It is current ly false in IE and jQuery simulatesbubbling)

        checkClone is equal to t rue if a browser correct ly clones the checked state of radiobuttons or checkboxes in document f ragments

        checkOn is equal to t rue if the value of a checkbox defaults to on when no value isspecif ied

        cors is equal to t rue if a browser can create an XMLHttpRequest object and if thatXMLHttpRequest object has a withCredent ials property To enable cross-domainrequests in environments that do not support cors yet but do allow cross-domain XHRrequests (windows gadget etc) set $support cors = t rue CORS WD

        cssFloat is equal to t rue if the name of the property containing the CSS f loat value iscssFloat as def ined in the CSS Spec (It is current ly false in IE it uses styleFloat instead)

        hrefNormalized is equal to t rue if the getAttribute() method retrieves the href at t ributeof elements unchanged rather than normalizing it to a fully-qualif ied URL (It is current lyfalse in IE the URLs are normalized)

        htmlSerialize is equal to t rue if the browser is able to serializeinsert ltlinkgt elementsusing the innerHTML property of elements (is current ly false in IE)

        leadingWhitespace is equal to t rue if the browser inserts content with innerHTMLexact ly as providedacirceurordquospecif ically if leading whitespace characters are preserved (It iscurrent ly false in IE 6-8)

        noCloneChecked is equal to t rue if cloned DOM elements copy over the state of thechecked expando (It is current ly false in IE) (Added in jQuery 151)

        noCloneEvent is equal to t rue if cloned DOM elements are created without eventhandlers (that is if the event handlers on the source element are not cloned) (It iscurrent ly false in IE)

        opacity is equal to t rue if a browser can properly interpret the opacity style property (Itis current ly false in IE it uses alpha f ilters instead)

        optDisabled is equal to t rue if opt ion elements within disabled select elements are notautomat ically marked as disabled

        optSelected is equal to t rue if an ltopt iongt element that is selected by default has aworking selected property

        scriptEval() is equal to t rue if inline scripts are automat ically evaluated and executedwhen inserted into the document using standard DOM manipulat ion methods such asappendChild() and createTextNode() (It is current ly false in IE it uses text to insertexecutable scripts)

        Note No longer supported removed in jQuery 16 Prior to jQuery 151 the scriptEval()method was the stat ic scriptEval property The change to a method allowed the test tobe deferred unt il f irst use to prevent content security policy inline-script violat ions

        style is equal to t rue if inline styles for an element can be accessed through the DOMattribute called style as required by the DOM Level 2 specif icat ion In this casegetAttribute(style) can retrieve this value in Internet Explorer cssText is used for thispurpose

        submitBubbles is equal to t rue if the submit event bubbles up the DOM tree as requiredby the W3C DOM event model (It is current ly false in IE and jQuery simulates bubbling)

        tbody is equal to t rue if an empty lttablegt element can exist without a lttbodygt elementAccording to the HTML specif icat ion this sub-element is opt ional so the property shouldbe true in a fully-compliant browser If false we must account for the possibility of thebrowser inject ing lttbodygt tags implicit ly (It is current ly false in IE which automat icallyinserts tbody if it is not present in a string assigned to innerHTML)

        Example 1 Returns the box model for the if rame

        Javascript

        $(p)html(This frame uses the W3C box model ltspangt + jQuerysupportboxModel + ltspangt)

        CSS

        p colorblue margin20px span colorred

        HTML

        ltpgt ltpgt

        Example 2 Returns false if the page is in QuirksMode in Internet Explorer

        Javascript

        jQuerysupportboxModel

        Results

        false

        Plugin Authoring

        • JQuery Documentation
          • Core
            • jQueryholdReady
            • jQuerywhen
            • jQuerysub
            • jQuerynoConflict
            • jQuery
              • Selector Context
              • Using DOM elements
              • Cloning jQuery Objects
              • Returning an Empty Set
                • jQuery
                  • Creating New Elements
                    • jQuery
                      • Selectors
                        • focus $(focus)
                        • selected $(selected)
                        • checked $(checked)
                        • disabled $(disabled)
                        • enabled $(enabled)
                        • file $(file)
                        • button $(button)
                        • reset $(reset)
                        • image $(image)
                        • submit $(submit)
                        • checkbox $(checkbox)
                        • radio $(radio)
                        • password $(password)
                        • text $(text)
                        • input $(input)
                        • only-child $(only-child)
                        • last-child $(last-child)
                        • first-child $(first-child)
                        • nth-child $(nth-child(indexevenoddequation))
                        • attributeContainsPrefix $([attribute|=value])
                        • attributeContainsWord $([attribute~=value])
                        • attributeMultiple $([attributeFilter1][attributeFilter2][attributeFilterN])
                        • attributeContains $([attribute=value])
                        • attributeEndsWith $([attribute$=value])
                        • attributeStartsWith $([attribute^=value])
                        • attributeNotEqual $([attribute=value])
                        • attributeEquals $([attribute=value])
                        • attributeHas $([attribute])
                        • visible $(visible)
                        • hidden $(hidden)
                        • parent $(parent)
                        • has $(has(selector))
                        • empty $(empty)
                        • contains $(contains(text))
                        • animated $(animated)
                        • header $(header)
                        • lt $(lt(index))
                        • gt $(gt(index))
                        • eq $(eq(index))
                        • odd $(odd)
                        • even $(even)
                        • not $(not(selector))
                        • Additional Notes
                        • last $(last)
                        • first $(first)
                        • next siblings $(prev ~ siblings)
                        • next adjacent $(prev + next)
                        • child $(parent gt child)
                        • descendant $(ancestor descendant)
                        • multiple $(selector1 selector2 selectorN)
                        • all $()
                        • class $(class)
                        • element $(element)
                        • id $(id)
                          • Traversing
                            • has
                            • parentsUntil
                            • prevUntil
                            • nextUntil
                            • each
                            • first
                            • last
                            • slice
                              • Negative Indices
                                • end
                                • andSelf
                                • siblings
                                • prevAll
                                • prev
                                • parents
                                • parent
                                • offsetParent
                                • nextAll
                                • next
                                • find
                                • contents
                                • closest
                                • closest
                                • children
                                • add
                                • not
                                  • Removing Specific Elements
                                    • map
                                    • is
                                      • Using a Function
                                        • eq
                                        • filter
                                          • Using a Filter Function
                                              • Attributes
                                                • removeProp
                                                • prop
                                                • prop
                                                  • Computed property values
                                                    • val
                                                    • val
                                                    • html
                                                    • html
                                                    • toggleClass
                                                    • removeClass
                                                    • hasClass
                                                    • removeAttr
                                                    • attr
                                                    • attr
                                                      • Setting a simple attribute
                                                      • Setting several attributes at once
                                                      • Computed attribute values
                                                        • addClass
                                                          • CSS
                                                            • jQuerycssHooks
                                                              • Feature Testing
                                                              • Defining a complete cssHook
                                                              • Special units
                                                              • Animating with cssHooks
                                                                • outerWidth
                                                                • outerHeight
                                                                • innerWidth
                                                                • innerHeight
                                                                • width
                                                                • width
                                                                • height
                                                                • height
                                                                • scrollLeft
                                                                • scrollLeft
                                                                • scrollTop
                                                                • scrollTop
                                                                • position
                                                                • offset
                                                                • offset
                                                                • css
                                                                • css
                                                                • toggleClass see Attributes
                                                                • removeClass see Attributes
                                                                • hasClass see Attributes
                                                                • addClass see Attributes
                                                                  • Manipulation
                                                                    • removeProp see Attributes
                                                                    • prop see Attributes
                                                                    • prop see Attributes
                                                                    • outerWidth see CSS
                                                                    • outerHeight see CSS
                                                                    • innerWidth see CSS
                                                                    • innerHeight see CSS
                                                                    • width see CSS
                                                                    • width see CSS
                                                                    • height see CSS
                                                                    • height see CSS
                                                                    • scrollLeft see CSS
                                                                    • scrollLeft see CSS
                                                                    • scrollTop see CSS
                                                                    • scrollTop see CSS
                                                                    • position see CSS
                                                                    • offset see CSS
                                                                    • offset see CSS
                                                                    • css see CSS
                                                                    • css see CSS
                                                                    • unwrap
                                                                    • detach
                                                                    • clone
                                                                    • remove
                                                                    • empty
                                                                    • replaceAll
                                                                    • replaceWith
                                                                    • wrapInner
                                                                    • wrapAll
                                                                    • wrap
                                                                    • insertBefore
                                                                    • before
                                                                      • Additional Arguments
                                                                        • insertAfter
                                                                        • after
                                                                          • Inserting Disconnected DOM nodes
                                                                          • Passing a Function
                                                                          • Additional Arguments
                                                                            • prependTo
                                                                            • prepend
                                                                              • Additional Arguments
                                                                                • appendTo
                                                                                • append
                                                                                  • Additional Arguments
                                                                                    • val see Attributes
                                                                                    • val see Attributes
                                                                                    • text
                                                                                    • text
                                                                                    • html see Attributes
                                                                                    • html see Attributes
                                                                                    • toggleClass see Attributes
                                                                                    • removeClass see Attributes
                                                                                    • hasClass see Attributes
                                                                                    • removeAttr see Attributes
                                                                                    • attr see Attributes
                                                                                    • attr see Attributes
                                                                                    • addClass see Attributes
                                                                                      • Data
                                                                                        • jQueryhasData
                                                                                        • jQueryremoveData
                                                                                        • jQuerydata
                                                                                        • jQuerydata
                                                                                        • jQuerydequeue
                                                                                        • jQueryqueue
                                                                                        • jQueryqueue
                                                                                        • clearQueue
                                                                                        • removeData
                                                                                        • data
                                                                                        • data
                                                                                        • dequeue
                                                                                        • queue
                                                                                        • queue
                                                                                          • Forms
                                                                                            • submit
                                                                                            • select
                                                                                            • change
                                                                                            • blur
                                                                                            • focus
                                                                                            • serializeArray
                                                                                            • serialize
                                                                                            • jQueryparam
                                                                                            • val see Attributes
                                                                                            • val see Attributes
                                                                                              • Events
                                                                                                • toggle
                                                                                                • eventnamespace
                                                                                                • undelegate
                                                                                                • delegate
                                                                                                • jQueryproxy
                                                                                                • focusout
                                                                                                • focusin
                                                                                                • eventisImmediatePropagationStopped
                                                                                                • eventstopImmediatePropagation
                                                                                                • eventisPropagationStopped
                                                                                                • eventstopPropagation
                                                                                                • eventisDefaultPrevented
                                                                                                • eventpreventDefault
                                                                                                • eventtimeStamp
                                                                                                • eventresult
                                                                                                • eventwhich
                                                                                                • eventpageY
                                                                                                • eventpageX
                                                                                                • eventcurrentTarget
                                                                                                • eventrelatedTarget
                                                                                                • eventdata
                                                                                                • eventtarget
                                                                                                • eventtype
                                                                                                • keydown
                                                                                                • scroll
                                                                                                • resize
                                                                                                • keyup
                                                                                                • keypress
                                                                                                • submit see Forms
                                                                                                • select see Forms
                                                                                                • change see Forms
                                                                                                • blur see Forms
                                                                                                • focus see Forms
                                                                                                • mousemove
                                                                                                • hover
                                                                                                • hover
                                                                                                • mouseleave
                                                                                                • mouseenter
                                                                                                • mouseout
                                                                                                • mouseover
                                                                                                • dblclick
                                                                                                • click
                                                                                                • mouseup
                                                                                                • mousedown
                                                                                                • error
                                                                                                • unload
                                                                                                • load
                                                                                                • ready
                                                                                                  • Aliasing the jQuery Namespace
                                                                                                    • die
                                                                                                    • die
                                                                                                    • live
                                                                                                      • Event Delegation
                                                                                                      • Multiple Events
                                                                                                      • Event Data
                                                                                                      • Event Context
                                                                                                      • Caveats
                                                                                                        • triggerHandler
                                                                                                        • trigger
                                                                                                        • one
                                                                                                        • unbind
                                                                                                          • Using Namespaces
                                                                                                          • Using the Event Object
                                                                                                            • bind
                                                                                                              • Multiple Events
                                                                                                              • Event Handlers
                                                                                                              • The Event object
                                                                                                              • Passing Event Data
                                                                                                                  • Deferred Object
                                                                                                                    • deferredpipe
                                                                                                                    • deferredalways
                                                                                                                    • promise
                                                                                                                    • deferredpromise
                                                                                                                    • jQuerywhen see Core
                                                                                                                    • deferredresolveWith
                                                                                                                    • deferredrejectWith
                                                                                                                    • deferredfail
                                                                                                                    • deferreddone
                                                                                                                    • deferredthen
                                                                                                                    • deferredreject
                                                                                                                    • deferredisRejected
                                                                                                                    • deferredisResolved
                                                                                                                    • deferredresolve
                                                                                                                      • Effects
                                                                                                                        • fadeToggle
                                                                                                                          • Easing
                                                                                                                          • Callback Function
                                                                                                                            • jQueryfxinterval
                                                                                                                            • delay
                                                                                                                            • jQueryfxoff
                                                                                                                            • clearQueue see Data
                                                                                                                            • dequeue see Data
                                                                                                                            • queue see Data
                                                                                                                            • queue see Data
                                                                                                                            • stop
                                                                                                                            • animate
                                                                                                                              • Animation Properties and Values
                                                                                                                              • Duration
                                                                                                                              • Complete Function
                                                                                                                              • Basic Usage
                                                                                                                              • Step Function
                                                                                                                              • Easing
                                                                                                                              • Per-property Easing
                                                                                                                                • fadeTo
                                                                                                                                • fadeOut
                                                                                                                                  • Easing
                                                                                                                                  • Callback Function
                                                                                                                                    • fadeIn
                                                                                                                                      • Easing
                                                                                                                                      • Callback Function
                                                                                                                                        • slideToggle
                                                                                                                                          • Easing
                                                                                                                                          • Callback Function
                                                                                                                                            • slideUp
                                                                                                                                              • Easing
                                                                                                                                              • Callback Function
                                                                                                                                                • slideDown
                                                                                                                                                  • Easing
                                                                                                                                                  • Callback Function
                                                                                                                                                    • toggle
                                                                                                                                                    • hide
                                                                                                                                                    • show
                                                                                                                                                      • Ajax
                                                                                                                                                        • jQueryajaxPrefilter
                                                                                                                                                        • ajaxComplete
                                                                                                                                                        • serializeArray see Forms
                                                                                                                                                        • serialize see Forms
                                                                                                                                                        • jQueryajaxSetup
                                                                                                                                                        • ajaxSuccess
                                                                                                                                                        • ajaxStop
                                                                                                                                                        • ajaxStart
                                                                                                                                                        • ajaxSend
                                                                                                                                                        • ajaxError
                                                                                                                                                        • jQuerypost
                                                                                                                                                          • The jqXHR Object
                                                                                                                                                            • jQuerygetScript
                                                                                                                                                            • jQuerygetJSON
                                                                                                                                                              • JSONP
                                                                                                                                                              • The jqXHR Object
                                                                                                                                                                • jQueryget
                                                                                                                                                                  • The jqXHR Object
                                                                                                                                                                    • load
                                                                                                                                                                      • Loading Page Fragments
                                                                                                                                                                        • jQueryajax
                                                                                                                                                                          • The jqXHR Object
                                                                                                                                                                          • Callback Function Queues
                                                                                                                                                                          • Data Types
                                                                                                                                                                          • Sending Data to the Server
                                                                                                                                                                          • Advanced Options
                                                                                                                                                                          • Extending Ajax
                                                                                                                                                                            • jQueryparam see Forms
                                                                                                                                                                              • Miscellaneous
                                                                                                                                                                                • each see Traversing
                                                                                                                                                                                • toArray
                                                                                                                                                                                • index
                                                                                                                                                                                  • Return Values
                                                                                                                                                                                  • Detail
                                                                                                                                                                                    • removeData see Data
                                                                                                                                                                                    • data see Data
                                                                                                                                                                                    • data see Data
                                                                                                                                                                                    • get
                                                                                                                                                                                    • size
                                                                                                                                                                                    • jQuerynoConflict see Core
                                                                                                                                                                                    • jQueryparam see Forms
                                                                                                                                                                                      • Dimensions
                                                                                                                                                                                        • outerWidth see CSS
                                                                                                                                                                                        • outerHeight see CSS
                                                                                                                                                                                        • innerWidth see CSS
                                                                                                                                                                                        • innerHeight see CSS
                                                                                                                                                                                        • width see CSS
                                                                                                                                                                                        • width see CSS
                                                                                                                                                                                        • height see CSS
                                                                                                                                                                                        • height see CSS
                                                                                                                                                                                          • Offset
                                                                                                                                                                                            • offsetParent see Traversing
                                                                                                                                                                                            • scrollLeft see CSS
                                                                                                                                                                                            • scrollLeft see CSS
                                                                                                                                                                                            • scrollTop see CSS
                                                                                                                                                                                            • scrollTop see CSS
                                                                                                                                                                                            • position see CSS
                                                                                                                                                                                            • offset see CSS
                                                                                                                                                                                            • offset see CSS
                                                                                                                                                                                              • Utilities
                                                                                                                                                                                                • jQuerynow
                                                                                                                                                                                                • jQueryparseXML
                                                                                                                                                                                                • jQuerytype
                                                                                                                                                                                                • jQueryisWindow
                                                                                                                                                                                                • jQueryparseJSON
                                                                                                                                                                                                • jQueryproxy see Events
                                                                                                                                                                                                • jQuerycontains
                                                                                                                                                                                                • jQuerynoop
                                                                                                                                                                                                • jQueryglobalEval
                                                                                                                                                                                                • jQueryisXMLDoc
                                                                                                                                                                                                • jQueryremoveData see Data
                                                                                                                                                                                                • jQuerydata see Data
                                                                                                                                                                                                • jQuerydata see Data
                                                                                                                                                                                                • jQuerydequeue see Data
                                                                                                                                                                                                • jQueryqueue see Data
                                                                                                                                                                                                • jQueryqueue see Data
                                                                                                                                                                                                • clearQueue see Data
                                                                                                                                                                                                • jQueryisEmptyObject
                                                                                                                                                                                                • jQueryisPlainObject
                                                                                                                                                                                                • dequeue see Data
                                                                                                                                                                                                • queue see Data
                                                                                                                                                                                                • queue see Data
                                                                                                                                                                                                • jQuerybrowser
                                                                                                                                                                                                • jQuerybrowserversion
                                                                                                                                                                                                • jQuerytrim
                                                                                                                                                                                                • jQueryisFunction
                                                                                                                                                                                                • jQueryisArray
                                                                                                                                                                                                • jQueryunique
                                                                                                                                                                                                • jQuerymerge
                                                                                                                                                                                                • jQueryinArray
                                                                                                                                                                                                • jQuerymap
                                                                                                                                                                                                • jQuerymakeArray
                                                                                                                                                                                                • jQuerygrep
                                                                                                                                                                                                • jQueryextend
                                                                                                                                                                                                • jQueryeach
                                                                                                                                                                                                • jQueryboxModel
                                                                                                                                                                                                • jQuerysupport
                                                                                                                                                                                                  • Plugin Authoring

          top related