Sei sulla pagina 1di 5

jQuery

This article is about the JavaScript library. For the actor, tion denition are done in a single step in a single location
see Jake Weary.
in the code. jQuery also aims to incorporate other highly
used JavaScript functionality (e.g. fade ins and fade outs
jQuery is a cross-platform JavaScript library designed to when hiding elements, animations by manipulating CSS
properties).
simplify the client-side scripting of HTML.[3] jQuery is
the most popular JavaScript library in use today, with in- The principles of developing with jQuery are:
stallation on 65% of the top 10 million highest-tracked
sites on the Web.[4][5][6] jQuery is free, open-source soft Separation of JavaScript and HTML: The
ware licensed under the MIT License.[2]
jQuery library provides simple syntax for adding
event handlers to the DOM using JavaScript,
rather than adding HTML event attributes to call
JavaScript functions. Thus, it encourages developers to completely separate JavaScript code from
HTML markup.

jQuerys syntax is designed to make it easier to navigate a


document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also
provides capabilities for developers to create plug-ins on
top of the JavaScript library. This enables developers to
create abstractions for low-level interaction and animation, advanced eects and high-level, themeable widgets.
The modular approach to the jQuery library allows the
creation of powerful dynamic web pages and Web applications.

Brevity and clarity: jQuery promotes brevity and


clarity with features like chainable functions and
shorthand function names.
Elimination of cross-browser incompatibilities:
The JavaScript engines of dierent browsers differ slightly so JavaScript code that works for one
browser may not work for another. Like other
JavaScript toolkits, jQuery handles all these crossbrowser inconsistencies and provides a consistent interface that works across dierent browsers.

The set of jQuery core featuresDOM element selections, traversal and manipulationenabled by its selector engine (named Sizzle from v1.3), created a new
programming style, fusing algorithms and DOM data
structures. This style inuenced the architecture of other
JavaScript frameworks like YUI v3 and Dojo, later stimulating the creation of the standard Selectors API.[7]

Extensibility: New events, elements, and methods


can be easily added and then reused as a plugin.

Microsoft and Nokia bundle jQuery on their platforms.[8]


Microsoft includes it with Visual Studio[9] for use
within Microsofts ASP.NET AJAX and ASP.NET MVC
frameworks while Nokia has integrated it into the Web
Run-Time widget development platform.[10] jQuery has
also been used in MediaWiki since version 1.16.[11]

2 Features
jQuery includes the following features:

Overview

DOM element selections using the multi-browser


open source selector engine Sizzle, a spin-o of the
jQuery project[12]

jQuery, at its core, is a DOM (Document Object Model)


manipulation library. The DOM is a tree-structure representation of all the elements of a Web page and jQuery
simplies the syntax for nding, selecting, and manipulating these DOM elements. For example, jQuery can be
used for nding an element in the document with a certain
property (e.g. all elements with an h1 tag), changing one
or more of its attributes (e.g. color, visibility), or making
it respond to an event (e.g. a mouse click).

DOM manipulation based on CSS selectors that uses


elements names and attributes, such as id and class,
as criteria to select nodes in the DOM
Events
Eects and animations
Ajax

jQuery also provides a paradigm for event handling that


goes beyond basic DOM element selection and manipulation. The event assignment and the event callback func-

Deferred and Promise objects to control asynchronous processing


1

USAGE

JSON parsing

a CSS selector string. This returns a jQuery object referencing all the matching elements in the HTML page.
Extensibility through plug-ins
$(div.test), for example, returns a jQuery object with
all the div elements of class test. This node set can be
Utilities, such as feature detection
manipulated by calling methods on the returned jQuery
Compatibility methods that are natively available in object or on the nodes themselves.
modern browsers, but need fall backs for older ones,
such as inArray() and each()

3.3 No-conict mode

Multi-browser (not to be confused with crossbrowser) support


jQuery also includes .noConict() mode, which relinquishes control of $. This can be helpful, if jQuery is
used with other libraries that also use $ as an identier.
2.1 Browser support
In no-conict mode, developers can use jQuery as a replacement for $ without losing functionality.[17]
Both versions 1.x and 2.x of jQuery support current1 versions (meaning the current stable version of the
browser and the version that preceded it) of Firefox, 3.4 Typical start-point
Chrome, Safari, and Opera. Version 1.x also supports
Internet Explorer 6 or higher. However, jQuery version Typically, jQuery is used by putting initialization code
2.x dropped Internet Explorer 68 support and supports and event handling functions in $(handler). This is trigonly IE 9 and later versions.[13]
gered when the browser has constructed the DOM and
sends a load event.

Usage

3.1

$(function () { // jQuery code, event handling callbacks


here });

Including the library

Historically, $(document).ready(callback) has been the


de facto signature for running code when the DOM is
The jQuery library is a single JavaScript le containing all ready. However, since jQuery 3.0, developers are enof its common DOM, event, eects, and Ajax functions. couraged to use the much shorter $(handler) signature.[18]
It can be included within a Web page by linking to a local
copy or to one of the many copies available from public Callback functions for event handling on elements that
servers. jQuery has a content delivery network (CDN) aren't loaded yet can be registered inside .ready() as
hosted by MaxCDN.[14] Google[15] and Microsoft[16] host anonymous functions. These event handlers will only be
called when the event is triggered. For example, the folit as well.
lowing code adds an event handler for a mouse click on
<script src="jquery.js"></script>
an img image element.
$(function () { $('img').on('click', function () { // handle
It is also possible to include jQuery directly from a CDN: the click event on any img element in the page }); });
<script src="https://code.jquery.com/jquery-3.1.0.min.
js"></script>
The following syntaxes are equivalent, although only
$(handler) should be used:[18]

3.2

Usage styles

jQuery has two usage styles:


Via the $ function, which is a factory method for the
jQuery object. These functions, often called commands, are chainable as they all return jQuery objects.

$(handler)
$().ready(handler)
$(document).ready(handler)
$(selector).ready(handler)

3.5 Chaining

Via $.-prexed functions. These are utility functions,


jQuery commands typically return a jQuery object, so
which do not act upon the jQuery object directly.
commands can be chained:
Access to and manipulation of multiple DOM nodes in $('div.test').add('p.quote').addClass('blue').slideDown('slow');
jQuery typically begins with calling the $ function with

3
This line nds the union of all div tags with class attribute
test and all p tags with class attribute quote, adds the
class attribute blue to each matched element, and then
increases their height with an animation. The $ and add
functions aect the matched set, while the addClass and
slideDown aect the referenced nodes.
Certain jQuery functions return specic values (such as
$('#input-user-email').val()). In these cases, chaining will
not work as the value does not reference the jQuery object.

3.8.1 Asynchronous
Note that the above example uses the deferred nature
of $.ajax() to handle its asynchronous nature: .done()
and .fail() create callbacks that run only when the asynchronous process is complete.

4 jQuery plug-ins

jQuerys architecture allows developers to create plugin code to extend its function. There are thousands of
3.6 Creating new DOM elements
jQuery plug-ins available on the Web[19] that cover a
range of functions, such as Ajax helpers, Web services,
Besides accessing DOM nodes through jQuery object hi- datagrids, dynamic lists, XML and XSLT tools, drag and
erarchy, it is also possible to create new DOM elements, drop, events, cookie handling, and modal windows.
if a string passed as the argument to $() looks like HTML. An important source of jQuery plug-ins is the plugFor example, this line nds an HTML select element ins subdomain of the jQuery Project website.[19] The
with ID carmakes, and adds an option element with value plugins in this subdomain, however, were accidentally
VAG and text Volkswagen":
deleted in December 2011 in an attempt to rid the
site of spam.[20] The new site will include a GitHubhosted repository, which will require developers to resubmit their plugins and to conform to new submission requirements.[21] There are alternative plug-in search
engines[22] like jquer.in that take more specialized approaches, such as listing only plug-ins that meet certain
3.7 Utility functions
criteria (e.g. those that have a public code repository).
Functions prexed with $. are utility functions or func- jQuery provides a Learning Center that can help users
JavaScript and get started developing jQuery
tions that aect global properties and behaviour. The fol- understand
[23]
plugins.
lowing, for example, is a function used for iterating over
arrays called each in jQuery:
$('select#carmakes).append($('<option
/>').attr({value:"VAG"}).append(Volkswagen));

$.each([1,2,3], function() { console.log(this + 1); });


This writes 2, 3, 4 to the console.

3.8

Ajax

5 History
jQuery was originally released in January 2006 at
BarCamp NYC by John Resig and was inuenced by
Dean Edwards earlier cssQuery library.[24] It is currently
maintained by a team of developers led by Timmy Willison (with the jQuery selector engine, Sizzle, being led by
Richard Gibson).

It is possible to perform cross-browser Ajax requests using $.ajax. Its associated methods can be used to load and
jQuery has also an interesting software license history.[25]
manipulate remote data.
Originally under the CC BY-SA 2.5, it was relicensed to
$.ajax({ type: 'POST', url: '/process/submit.php', the MIT license in 2006.[26] On end of 2006 it was dualdata: { name : 'John', location : 'Boston', }, licensed under GPL and MIT license.[27] As this led to
}).done(function(msg) { alert('Data Saved: ' + some confusion, in 2012 the GPL was dropped and is
msg);
}).fail(function(xmlHttpRequest,
status- now only MIT licensed.[28]
Text, errorThrown) { alert( 'Your form submission failed.\n\n' + 'XML Http Request: ' + As of 2015, jQuery remains the most widely used
JSON.stringify(xmlHttpRequest) + ',\nStatus Text: JavaScript library on the Web.
' + statusText + ',\nError Thrown: ' + errorThrown); });

5.1 Release history

This example posts the data name=John and location=Boston to /process/submit.php on the server. When
this request nishes the success function is called to alert 6 Testing framework
the user. If the request fails it will alert the user to the
QUnit is a test automation framework used to test the
failure, the status of the request, and the specic error.

10

EXTERNAL LINKS

jQuery project. The jQuery team developed it as an [16] Microsoft Ajax Content Delivery Network. ASP.net.
Microsoft Corporation. Retrieved June 19, 2012.
in-house unit testing library.[29] The jQuery team uses
it to test its code and plugins, but it can test any
[17] jQuery.noConict() jQuery API Documentation.
generic JavaScript code, including server-side JavaScript
code.[29]
[18] $(document).ready deprecated
As of 2011, the jQuery Testing Team uses QUnit with
TestSwarm to test each jQuery codebase release.[30]

[20] What Is Happening To The jQuery Plugins Site?". Retrieved 22 April 2015.

See also

[21] jquery/plugins.jquery.com. GitHub. Retrieved 22 April


2015.

Comparison of JavaScript frameworks

[22] Kanakiya, Jay. jquery plugins.

jQuery Mobile

[23] jQuery Learning Center. jQuery Foundation. Retrieved 2014-07-02.

jQuery UI
Globalize

[19] Plugins. The jQuery Project. Retrieved 26 August


2010.

[24] York, Richard (2009). Beginning JavaScript and CSS Development with jQuery. Wiley. p. 28. ISBN 978-0-47022779-4.

References

[25] jquery history on softwarefreedom.org


[26] jquery-under-the-mit-license on jquery.org (2006)

[1] jQuery 3.1.0 Released No More Silent Errors


[2] License - jQuery Project. jQuery Foundation. Retrieved 2014-07-02.
[3] jQuery: The write less, do more, JavaScript library.
The jQuery Project. Retrieved 29 April 2010.

[27] license on jquery.org (archived 2010)


[28] jquery-licensing-changes on jquery.org (2012)
[29] History. qunitjs.com. Retrieved 2014-07-02.
[30] jQuery Testing Team Wiki

[4] Usage of JavaScript libraries for websites. Retrieved


2015-07-14.
[5] jQuery Usage Statistics. Retrieved 2013-05-17.
[6] http://libscore.com/#libs
[7] "Selectors API Level 1, W3C Recommendation" (21
February 2013). This standard turned what was jQuery
helper methods into JavaScript-native ones, and the
wide use of jQuery stimulated the fast adoption of querySelector/querySelectorAll into main Web browsers.
[8] Resig, John (2008-09-28). jQuery, Microsoft, and
Nokia. jQuery Blog. jQuery. Retrieved 2009-01-29.
[9] Guthrie, Scott (2008-09-28). jQuery and Microsoft.
ScottGus Blog. Retrieved 2009-01-29.
[10] Guarana UI: A jQuery Based UI Library for Nokia
WRT. Forum Nokia. Retrieved 2010-03-30.
[11] jQuery. MediaWiki. January 19, 2012. Retrieved
March 11, 2012.
[12] Resig, John (2009-01-14). jQuery 1.3 and the jQuery
Foundation. jQuery Blog. Retrieved 2009-05-04.
[13] Browser Support | jQuery

John Resig (speaker) (2007-04-13). Advancing


JavaScript with Libraries (Part 1) (Yahoo! Video).
YUI Theater. Retrieved 2009-05-04.
John Resig (speaker) (2007-04-13). Advancing
JavaScript with Libraries (Part 2) (Yahoo! Video).
YUI Theater. Retrieved 2009-05-04.
Krill, Paul (2006-08-31). JavaScript, .Net developers aided in separate project. InfoWorld. Retrieved
2009-05-04.
Taft, Darryl K. (2006-08-30). jQuery Eases
JavaScript, AJAX Development. eWeek. Retrieved 2009-05-04.

10 External links
Dmitri Gaskin Google Tech Talk, 2008 on YouTube
Ocial website

[14] jQuery CDN


[15] Google Libraries API - Developers
code.google.com. Retrieved March 11, 2012.

9 Further reading

Guide.

11
11.1

Text and image sources, contributors, and licenses


Text

JQuery Source: https://en.wikipedia.org/wiki/JQuery?oldid=742415908 Contributors: Edward, Greenman, StevenBlack, Haakon, Jonik,


Geary, Samsara, Bevo, Chealer, Rfc1394, TimR, Somercet, DocWatson42, Nickdc, RScheiber, Zumbo, Uzume, T1mmyb, Mzajac,
Bumm13, Euphoria, Discospinster, Rich Farmbrough, Hydrox, Smyth, Samboy, Bender235, Damotclese, Nigelj, Sky Apperley, L.Willms,
Matthewk, Gary, Polarscribe, RoySmith, Yadyn, Dmausner, Runtime, Versageek, Mattbrundage, Kazvorpal, Oleg Alexandrov, Unixxx,
Woohookitty, Mindmatrix, Glyphobet, Toussaint, Tokek, Qwertyus, Ravidew, Rjwilmsi, Cantorman, Husky, Volox, Riki, Chobot, Benlisquare, Mhking, Manop, Brec, Spazery, Rsrikanth05, Greenyoda, Bovineone, Wae, Retired username, Booch, Natkeeran, Leotohill,
Jeremy Visser, Blowdart, Xpclient, Mjsabby, Gkanai, Jeresig, Closedmouth, Gslin, CapitalLetterBeginning, Mikus, ViperSnake151, Coffeeower, AndrewWTaylor, SmackBot, KAtremer, Reedy, Dbvisel, Ohnoitsjamie, 32X, Jprg1966, Thumperward, DanielMettler, Deli
nk, Gutworth, Frap, Fraser Chapman, Emamian, KerathFreeman, Cybercobra, EIFY, Daniel.Cardenas, Joey-das-WBF, Kuru, Gobonobo,
Eleveneleven, Emil Stenstrm, Dreftymac, IvanLanin, Paul Foxworthy, BenStrauss, Sin2x, Fundaman, Sohum, 123santosh, Bill.albing,
Dgw, Andkore, Krauss, Koeplinger, Tomturton, Davidhorman, Daviddecraene, Gioto, Kohenkatz, Thomasmallen, Od1n, BCube, Wllm,
Jahoe, Magioladitis, Flesler, Tedickey, Rich257, Logictheo, User A1, Bitbit, Ian Bailey, Mazza007, Andytuba, J.delanoy, Trusilver, Silas S.
Brown, Plasticup, Uzbekjon, Equazcion, Adam Zivner, Jazzycat, VolkovBot, TXiKiBoT, VivekVish, Jobu0101, Vinodxx, Mantipula, Alex
Smotrov, M gol, Ferric84, Madhero88, PieterDeBruijn, Chenzw, AlleborgoBot, Ohiostandard, SieBot, Bobbravo2, Jack Merridew, Utkarsh
kapadia, Mochan Shrestha, Csloomis, Anakin101, Kayalshri, Cloudream, Kdvolder, Tdavey, Janebfoster, ChandlerMapBot, Alexbot, Chininazu12, El bot de la dieta, Miami33139, Psychcf, Zerore0, XLinkBot, Dubeerforme, Deineka, Addbot, Mortense, Mabdul, Grandscribe,
AkhtaBot, Summit677, AgadaUrbanit, Numbo3-bot, Matj Grabovsk, Teles, Mlavannis, LeonardoG, Luckas-bot, Yobot, Midinastasurazz, Fraggle81, Amirobot, AnomieBOT, Message From Xenu, JackieBot, Venom087, Mann jess, Nhantdn, Suit, Phistuck, MauritsBot,
Xqbot, TobiaszCudnik, Xedret, FromSpace, GrouchoBot, Frosted14, Omar Booklie, RibotBOT, A Quest For Knowledge, Phette23, Danny
B., Iggymwangi, Oehr, Krinkle, KJedi, Arjen IF, Mark Renier, Lucy75, Ilovenagpur, Reltech001, Sae1962, Dominik Moritz, Timoothy36,
Democraticmacguitarist, Mercatus3, John85, Manywindows, Zoonosis, Chenopodiaceous, Atif.mod, De Katten, I dream of horses, StefanGroen, Tra, Logicbus, Hoo man, BRUTE, Garazy, Has72, EdoDodo, P23y1, Cnwilliams, Rekihattori, Herakleitoszefesu, Dinamikbot, Zvn, Crysb, Genhuan, Web010, Tbhotch, Perhelion, Tomchen1989, Lopifalko, Pwt-wsu-sp, EmausBot, Dewritech, Alekseenkokirill,
N535, ZroBot, QuentinUK, Haxrat, Cfust, Derekleungtszhei, Aavindraa, Didgeedoo, Mgeditor, AshramHQ, Donner60, Coyote12, ChuispastonBot, Senator2029, Littke, Jdbenson, ClueBot NG, Lfortin79, CocuBot, MelbourneStar, Catlemur, Shaddim, Frietjes, Rcorym15,
Widr, Rudrapratap1986, Sergio ykz, Stephan2307, Seostick, Gproulx, MiyuruSankalpa, Calabe1992, Troy.hester, BG19bot, MusikAnimal, Mark Arsten, Chmarkine, Dsharmara, ComponentOne, Sonialoud, Sdesalas, Vannhuthanh, Peter Bowman, Liudvikam, Bikeit, JYBot, Amejia1, SoledadKabocha, Makecat-bot, Sriarc, Andrededits, Frosty, Fhenskens, Dmethvin, MySIDis0x11, BurritoBazooka, Vanamonde93, Assman10101, Lostinthecode, Nhalink, Franois Robere, Karina57, Jzaeerer, ExtraBart, Rpot3, CrystalCanine, Lesser Cartographies, Nstrazimiri, NordLeuchte, Tamersaadeh, TheWiki122, Byspiritn, Sapper-, Stiegenaufgang, Klunkthespacecat, Eyalweiss,
Vov9, Waldron.rick, Corax rarus, Dstudentx, Paleolithicus, Llaxmikant, Mediavalia, Executionary, KasparBot, KarthickVkumar, Equinox,
Bpreston5, Fuortu, Emotionalllama, Davidpotesta and Anonymous: 365

11.2

Images

File:Commons-logo.svg Source: https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg License: CC-BY-SA-3.0 Contributors: ? Original artist: ?


File:Free_and_open-source_software_logo_(2009).svg Source: https://upload.wikimedia.org/wikipedia/commons/3/31/Free_and_
open-source_software_logo_%282009%29.svg License: Public domain Contributors: FOSS Logo.svg Original artist: Free Software Portal
Logo.svg (FOSS Logo.svg): ViperSnake151
File:JQuery_logo.svg Source: https://upload.wikimedia.org/wikipedia/en/9/9e/JQuery_logo.svg License: Fair use Contributors:
Found in jQuery_Identity.zip on the about page of jQuery Original artist: ?
File:Question_book-new.svg Source: https://upload.wikimedia.org/wikipedia/en/9/99/Question_book-new.svg License: Cc-by-sa-3.0
Contributors: ? Original artist: ?
File:Symbol_list_class.svg Source: https://upload.wikimedia.org/wikipedia/en/d/db/Symbol_list_class.svg License: Public domain Contributors: ? Original artist: ?

11.3

Content license

Creative Commons Attribution-Share Alike 3.0

Potrebbero piacerti anche