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
105
votes
8 answers

Uncaught TypeError: Cannot read property 'top' of undefined

I apologize if this question has already been answered. I've tried searching for solutions but could not find any that suited my code. I'm still new to jQuery. I have two different types of sticky menus for two different pages. Here's the code for…
edubba
  • 1,217
  • 2
  • 9
  • 8
105
votes
11 answers

Pass Multiple Parameters to jQuery ajax call

I have the following jquery code to call a webmethod in an aspx page $.ajax({ type: "POST", url: "popup.aspx/GetJewellerAssets", contentType: "application/json; charset=utf-8", data: '{"jewellerId":' + filter + '}', dataType:…
ChrisCa
  • 10,187
  • 19
  • 76
  • 112
105
votes
15 answers

Twitter Bootstrap alert message close and open again

I have a problem with alert messages. It is displayed normally, and I can close it when the user presses x (close), but when the user tries to display it again (for example, click on the button event) then it is not shown. (Moreover, if I print this…
user721588
105
votes
10 answers

Selecting empty text input using jQuery

How do I identify empty textboxes using jQuery? I would like to do it using selectors if it is at all possible. Also, I must select on id since in the real code where I want to use this I don't want to select all text inputs. In my following two…
Cros
  • 4,267
  • 8
  • 37
  • 47
105
votes
5 answers

Javascript Array Concat not working. Why?

So I've created this jqueryui widget. Its creates a div that I can stream errors into. The widget code looks like this: $.widget('ui.miniErrorLog', { logStart: "
    ", // these next 4 elements are actually a bunch more complicated. logEnd: …
Rafael Baptista
  • 10,259
  • 4
  • 35
  • 56
105
votes
5 answers

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

I created an mvc4 web api project using vS2012. I used following tutorial to solve the Cross-Origin Resource Sharing, "http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx". It is working…
Kishore
  • 1,197
  • 2
  • 10
  • 15
104
votes
10 answers

Detect backspace and del on "input" event?

How to do that? I tried: var key = event.which || event.keyCode || event.charCode; if(key == 8) alert('backspace'); but it doesn't work... If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the…
Alex
  • 60,472
  • 154
  • 401
  • 592
104
votes
11 answers

How to clear File Input

Below is part of the jquery code I have which displays the file input and a "Clear File" button. var $imagefile = $('').attr({ type: 'file', name: 'imageFile', class: 'imageFile' }); $image.append($imagefile); var $imageclear…
user1181690
  • 1,093
  • 2
  • 9
  • 12
104
votes
7 answers

Jquery select all elements that have $jquery.data()

Select elements that i have previously set with jquery.data(); i.e. Select all elements with .data('myAttr') already been set. SOLUTION A jsfiddle to demostrate is Fiddle
Argiropoulos Stavros
  • 9,119
  • 11
  • 57
  • 78
104
votes
14 answers

Programmatically trigger "select file" dialog box

I have a hidden file input element. Is it possible to trigger its select file dialog box from a button's click event?
tamakisquare
  • 15,251
  • 24
  • 79
  • 125
104
votes
5 answers

Differences between detach(), hide() and remove() - jQuery

What is the functional difference between these three jQuery methods: detach() hide() remove()
Vivek
  • 10,426
  • 14
  • 44
  • 65
104
votes
7 answers

How to get mouse position in jQuery without mouse-events?

I would like to get current mouse position but I don't want to use: $(document).bind('mousemove',function(e){ $("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY); }); because I just need to get the position and process the…
Martin Vseticka
  • 25,160
  • 25
  • 118
  • 187
104
votes
2 answers

jQuery.active function

I was trying to find some more information on the following jQuery function: jQuery.active It is described to test the number of active connections to a server and will evaluate true when the number of connections is zero. I could not find any…
RyanP13
  • 6,285
  • 20
  • 74
  • 138
104
votes
4 answers

jQuery form serialize - empty string

My html:
user137348
  • 9,610
  • 17
  • 62
  • 88
104
votes
6 answers

Get an array of list element contents in jQuery

I have a structure like this:
  • text1
  • text2
  • text3
How do I use javascript or jQuery to get the text as an array? ['text1', 'text2', 'text3'] My plan after this is to assemble it into a string, probably…
Christian Oudard
  • 42,650
  • 23
  • 62
  • 69
1 2 3
99
100