Questions tagged [jquery]

jQuery is a JavaScript library, consider also adding the JavaScript tag. jQuery is a popular cross-browser JavaScript library that facilitates Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. A question tagged jQuery should be related to jQuery, so jQuery should be used by the code in question and at least jQuery usage-related elements need to be in the question.

About

jQuery (Core) is a cross-browser JavaScript library (created by John Resig) that provides abstractions for common client-side tasks such as DOM traversal, DOM manipulation, event handling, animation and AJAX.

jQuery simplifies HTML document traversal and manipulation, event handling, animation, and AJAX due to its API that works across a multitude of browsers.

jQuery provides a platform to create plugins that extend its capabilities beyond those already provided by the library. The development of jQuery and related projects is coordinated by the jQuery Foundation.

Features

jQuery includes the following features:

  • DOM element selections using the multi-browser open source selector engine Sizzle, a spin-off of the jQuery project
  • DOM traversal and modification (including support for CSS 1–3)
  • DOM manipulation based on CSS selectors that use node element names and attributes (e.g. ID and class) as criteria to build selectors
  • Events
  • Effects and animations
  • AJAX
  • JSON parsing (for older browsers)
  • Extensibility through plug-ins
  • Utilities such as user agent information, feature detection
  • Compatibility methods that are natively available in modern browsers but need fallbacks for older ones - For example the inArray() and each() functions
  • Multi-browser (not to be confused with cross-browser) support

Browser Support

jQuery supports the current stable version, and the preceding version or "current - 1 version," of Chrome, Edge, Firefox, and Safari. It also supports the current stable version of Opera.

In addition, jQuery 1.x supports Internet Explorer version 6 or higher. However, support for IE 6-8 was dropped by jQuery 2.x and by jQuery 3.x, which support only IE 9 or higher.

Finally, jQuery supports the stock mobile browser on Android 4.0 and higher, and Safari on iOS 7 and higher.

jQuery Versions

jQuery is updated frequently, so the library should be used carefully. Some functions become deprecated with newer versions of jQuery. Follow the release notes to be on track with the features.

The jQuery CDN provides download links for all versions of jQuery, including the latest stable versions of each branch.

When asking jQuery related questions, you should:

  1. Read the jQuery API documentation carefully and search Stack Overflow for duplicates before asking.
  2. Isolate the problematic code and reproduce it in an online environment such as JSFiddle, JSBin, or CodePen. For Live Connect you can also use LiveWeave. However, be sure to include the problematic code in your question — don't just link to the online environment. You can also use Stack Snippets to include the runnable code in the question itself.
  3. Tag the question appropriately; always include , and use the other web development tags (, , ) as applicable. The most popular jQuery plugins also have their own tags, such as , , and ; for every other plugin include the tag .
  4. Indicate the version of the jQuery library used, so that any answers can provide version-appropriate solutions.
  5. Mention which browser the code is having problems on and what error messages, if any, were thrown by the browser. If the problems are consistent in a cross-browser way, then that's valuable information too.

Frequently Asked Questions

Hello world example

This shows "Hello world!" in the alert box on each link click after the DOM is ready (JSFiddle):

// callback for document load
$(function () {
    // select anchors and set click handler
    $("a").click(function (event) { 
        // prevent link default action (redirecting to another page)
        event.preventDefault();

        // show the message
        alert("Hello world!"); 
    });
});

Resources

Video Tutorial

Popular plugins

Other jQuery Foundation projects

Best practices and commonly made mistakes

Related question: jQuery pitfalls to avoid

Remember to use a ready handler

If your code is somehow manipulating the DOM, then you need to ensure that it is run after the DOM finishes loading.

jQuery provides ways to do that with an anonymous function:

$(function () { 
    /* code here */ 
});

// Or
$(document).ready(function () { 
    /* code here */ 
});

or with a named function:

$(functionName);

// Or
$(document).ready(functionName);

These are alternatives to placing the JavaScript code or script tag in the HTML right before the closing </body> tag.

In jQuery 3.x, the recommended way to add a ready handler is $(function () {}), while other forms such as $(document).ready(function () {}) are deprecated. Also, jQuery 3.x removes the ability to use .on("ready", function () {}) to run a function on the "ready" event.

Avoid conflicts by using noConflict() and a different alias for jQuery

If your jQuery code conflicts with another library that also uses the $ sign as an alias, then use the noConflict() method:

jQuery.noConflict();

Then you can safely use $ as an alias for the other library while using the name jQuery itself for jQuery functions.

Alternatively, you can call

$jq = jQuery.noConflict();

and use $jq as an alias for jQuery. For example:

$jq(function () {
    $jq("a").click(function (event) { 
        event.preventDefault();
        alert("Hello world!"); 
    });
});

It is also possible to assign jQuery to $ within a certain scope:

jQuery(function ($) {
    // In here, the dollar sign is an alias for jQuery only.
});

// Out here, other libraries can use the dollar sign as an alias.

Then you can use $ as an alias for jQuery inside that function block, without worrying about conflicts with other libraries.

Cache your jQuery objects and chain whenever possible

Calling the jQuery function $() is expensive. Calling it repeatedly is extremely inefficient. Avoid doing this:

$('.test').addClass('hello');
$('.test').css('color', 'orange');
$('.test').prop('title', 'Hello world');

Instead cache your jQuery object in a variable:

var $test = $('.test');

$test.addClass('hello');
$test.css('color', 'orange');
$test.prop('title', 'Hello world');

Or better yet, use chaining to reduce repetition:

$('.test').addClass('hello').css('color', 'orange').prop('title', 'Hello world');

Also, remember that many functions can perform multiple changes in one call, by grouping all the values into an object. Instead of:

$('.test').css('color', 'orange').css('background-color', 'blue');

use:

$('.test').css({ 'color': 'orange', 'background-color': 'blue' });

Variable naming conventions

jQuery wrapped variables are usually named starting with $ to distinguish them from standard JavaScript objects.

var $this = $(this);

Know your DOM properties and functions

While one of the goals of jQuery is to abstract away the DOM, knowing DOM properties can be extremely useful. One of the most commonly made mistakes by those who learn jQuery without learning about the DOM is to utilize jQuery to access properties of an element:

$('img').click(function () {
    $(this).attr('src');  // Bad!
});

In the above code, this refers to the element from which the click event handler was fired. The code above is both slow and verbose; the code below functions identically and is much shorter, faster and more readable.

$('img').click(function () {
    this.src; // Much, much better
});

Idiomatic syntax for creating elements

Although the following two examples seem to be functionally equivalent and syntactically correct, the first example is preferred:

$('<p>', {
    text: 'This is a ' + variable, 
    "class": 'blue slider', 
    title: variable, 
    id: variable + i
}).appendTo(obj);

By comparison, a string concatenation approach is much less readable and far more brittle:

$('<p class="blue slider" id="' + variable + i + '" title="' + variable + '">This is a ' + variable + '</p>').appendTo(obj);

While the first example will be slower than the second, the benefits of greater clarity will likely outweigh the nominal speed differences in all but the most performance-sensitive applications.

Moreover, the idiomatic syntax is robust against the injection of special characters. For instance, in the 2nd example, a quote character in variable would prematurely close the attributes. Doing the proper encoding by yourself remains possible even if not recommended because it is prone to error.

Chat Rooms

Chat about jQuery with other Stack Overflow users:

Alternatives/Competitors

Other well-known JavaScript libraries are:

Public repositories:

  • cdnjs - Cloudflare community driven project, currently used by ~1,143,000 websites worldwide.
  • jsdelivr - An equally free and open source alternative CDN to cdnjs.

Related Tags

1012658 questions
2479
votes
32 answers

jQuery scroll to element

I have this input element: Then I have some other elements, like other text inputs, textareas, etc. When the user clicks on that input with #subject, the page should scroll…
DiegoP.
  • 42,459
  • 34
  • 85
  • 101
2393
votes
19 answers

Disable/enable an input with jQuery?

$input.disabled = true; or $input.disabled = "disabled"; Which is the standard way? And, conversely, how do you enable a disabled input?
omg
  • 123,990
  • 135
  • 275
  • 341
2387
votes
34 answers

Get selected text from a drop-down list (select box) using jQuery

How can I get the selected text (not the selected value) from a drop-down list in jQuery?
haddar
  • 24,077
  • 3
  • 18
  • 12
2384
votes
18 answers

.prop() vs .attr()

So jQuery 1.6 has the new function prop(). $(selector).click(function(){ //instead of: this.getAttribute('style'); //do i use: $(this).prop('style'); //or: $(this).attr('style'); }) or in this case do they do the same…
Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295
2320
votes
33 answers

How can I determine if a variable is 'undefined' or 'null'?

How do I determine if variable is undefined or null? My code is as follows: var EmpName = $("div#esd-names div#name").attr('class'); if(EmpName == 'undefined'){ // DO SOMETHING };
But if I do…
sadmicrowave
  • 35,768
  • 34
  • 99
  • 172
2299
votes
19 answers

How to get the children of the $(this) selector?

I have a layout similar to this:
and would like to use a jQuery selector to select the child img inside the div on click. To get the div, I've got this selector: $(this) How can I get the child img using a…
Alex
  • 25,366
  • 5
  • 27
  • 36
2180
votes
20 answers

Get the size of the screen, current web page and browser window

How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY which will work in all major browsers?
turtledove
  • 23,054
  • 3
  • 18
  • 20
2176
votes
39 answers

$(document).ready equivalent without jQuery

I have a script that uses $(document).ready, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency. How can I implement my own $(document).ready functionality without using jQuery? I know that …
FlySwat
  • 160,042
  • 69
  • 241
  • 308
2149
votes
14 answers

How can I select an element with multiple classes in jQuery?

I want to select all the elements that have the two classes a and b. So, only the elements that have both classes. When I use $(".a, .b") it gives me the union, but I want the intersection.
Mladen
  • 24,320
  • 11
  • 36
  • 47
2070
votes
41 answers

How do I format a Microsoft JSON date?

I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like…
Mark Struzinski
  • 31,745
  • 33
  • 103
  • 135
1941
votes
32 answers

Get current URL with jQuery?

I am using jQuery. How do I get the path of the current URL and assign it to a variable? Example URL: http://localhost/menuname.de?foo=bar&number=0
venkatachalam
  • 101,405
  • 29
  • 70
  • 76
1897
votes
18 answers

Abort Ajax requests using jQuery

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?
lukewm
  • 20,467
  • 6
  • 24
  • 28
1806
votes
28 answers

Preview an image before it is uploaded

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image. How can I do this?
Simbian
  • 18,275
  • 3
  • 15
  • 8
1790
votes
15 answers

How to move an element into another element?

I would like to move one DIV element inside another. For example, I want to move this (including all children):
...
into this:
...
so that I have this:
Mark Richman
  • 26,790
  • 23
  • 85
  • 150
1779
votes
59 answers

What is the best way to detect a mobile device?

Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device. The jQuery $.browser function is not…
superUntitled
  • 21,375
  • 26
  • 81
  • 106