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
8089
votes
60 answers

How do I check if an element is hidden in jQuery?

Is it possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle()? How would you test if an element is visible or hidden?
Philip Morton
  • 121,023
  • 36
  • 84
  • 96
7711
votes
58 answers

How do I redirect to another webpage?

How can I redirect the user from one page to another using jQuery or pure JavaScript?
venkatachalam
  • 101,405
  • 29
  • 70
  • 76
5960
votes
42 answers

How to return the response from an asynchronous call?

I have a function foo which makes an asynchronous request. How can I return the response/result from foo? I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that…
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
4831
votes
67 answers

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox. But the following…
Prasad
  • 56,343
  • 61
  • 142
  • 199
4511
votes
15 answers

"Thinking in AngularJS" if I have a jQuery background?

Suppose I'm familiar with developing client-side applications in jQuery, but now I'd like to start using AngularJS. Can you describe the paradigm shift that is necessary? Here are a few questions that might help you frame an answer: How do I…
Mark Rajcok
  • 348,511
  • 112
  • 482
  • 482
4301
votes
42 answers

Setting "checked" for a checkbox with jQuery

I'd like to do something like this to tick a checkbox using jQuery: $(".myCheckBox").checked(true); or $(".myCheckBox").selected(true); Does such a thing exist?
tpower
  • 53,004
  • 18
  • 65
  • 99
3372
votes
20 answers

How to insert an item into an array at a specific index (JavaScript)?

I am looking for a JavaScript array insert method, in the style of: arr.insert(index, item) Preferably in jQuery, but any JavaScript implementation will do at this point.
tags2k
  • 70,860
  • 30
  • 74
  • 105
3082
votes
14 answers

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well: 1. event.preventDefault() $('a').click(function (e) { …
RaYell
  • 66,181
  • 20
  • 123
  • 149
3020
votes
34 answers

How can I upload files asynchronously?

I would like to upload a file asynchronously with jQuery. $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url:…
Sergio del Amo
  • 71,609
  • 66
  • 148
  • 177
2910
votes
44 answers

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function?
Jake McGraw
  • 52,590
  • 10
  • 46
  • 62
2854
votes
39 answers

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery? I can get all of them like this: $("form :radio") How do I know which one is selected?
juan
  • 74,179
  • 49
  • 153
  • 188
2765
votes
11 answers

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No…
Mr Jedi
  • 28,628
  • 8
  • 25
  • 36
2650
votes
87 answers

How do I detect a click outside an element?

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with…
Sergio del Amo
  • 71,609
  • 66
  • 148
  • 177
2569
votes
30 answers

How can I refresh a page with jQuery?

How can I refresh a page with jQuery?
luca
  • 34,346
  • 27
  • 81
  • 123
2531
votes
40 answers

Add table row in jQuery

What is the best method in jQuery to add an additional row to a table as the last row? Is this acceptable? $('#myTable').append('my datamore data'); Are there limitations to what you can add to a table like this (such as…
Darryl Hein
  • 134,677
  • 87
  • 206
  • 257
1
2 3
99 100