Frequently Asked Questions
From jQuery JavaScript Library
These are some questions frequently asked by others while using jQuery to do cool things. If you have a new question, please post it to the Mailing List.
How do I ... ?
How do I test whether an element has a particular class?
(Sometimes also: Does jQuery have a hasClass method?)
- You can use the is() method along with an appropriate selector
if ( $('#myDiv').is('.pretty') )
$('#myDiv').show();
Note that this method allows you to test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):
if ( $('#myDiv').is(':hidden') )
$('#myDiv').show();
("div").click(function(){
if ( $(this).hasClass("protected") )
$(this)
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: 0 });
});
How do I test whether an element exists?
- You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length )
$('#myDiv').show();
Note: It isn't always necessary to test whether an element exists. The following code would show the item if it exists, and do nothing (no errors) if it did not:
$('#myDiv').show();
How do I determine the state of a toggled element?
You can check the state using the :visible or :hidden selectors.
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, just include ":visible" or ":hidden" in the selector expression. For example:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
How do I select an element that has weird characters in its ID?
For example, it can be common for some frameworks to generate unique IDs that have special characters in them (like '.' or '[..]'). The problem is that these characters have a special meaning in CSS.
Thankfully, jQuery has a workaround, which allows you to do the following:
// Does not work
$("#some.id")
// Works!
$("#some\\.id")
and another example:
// Does not work
$("#some[id]")
// Works!
$("#some\\[id\\]")
How do I disable/enable an element?
You can disable/enable an element by setting the 'disabled' attribute to 'disabled' (to disable it) or "" (to enable it). The result of which looks something like this:
// Disable #x
$("#x").attr("disabled","disabled");
// Enable #x
$("#x").removeAttr("disabled");
You can try an example of enabling/disabling with the following demo:
and here's the source code to the demo:
<select id="x" style="width:200px;">
<option>one</option>
<option>two</option>
</select>
<input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
<input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>
How do I check/uncheck an input?
You can check/uncheck an element by setting the 'checked' attribute to 'checked' (to check it) or "" (to uncheck it). The result of which looks something like this:
// Check #x
$("#c").attr("checked", "checked");
// Uncheck #x
$("#c").attr("checked","");
You can try an example of checking/unchecking with the following demo:
and here's the source code to the demo:
<label><input type="checkbox" id="c"/> I'll be checked/unchecked.</label>
<input type="button" value="Check" onclick='$("#c").attr("checked","checked")'/>
<input type="button" value="Uncheck" onclick='$("#c").attr("checked","")'/>
How do I get the text value of a selected option?
Select elements typically have two values that you want to access. First there's the value, which is easy:
$("select#myselect").val();
// => 1
Next is getting the textual value of a select. For example, if you had the following select box:
<select id="myselect"> <option value="1">Mr</option> <option value="2">Mrs</option> <option value="3">Ms</option> <option value="4">Dr</option> <option value="5">Prof</option> </select>
And you wanted to get the string "Mr" if the first option was selected (instead of just "1"). You would do that in the following way:
$("#myselect option:selected").text();
// => "Mr"
You can see this in action in the following demo:
and here's the full source code to the demo:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
<input type="button" value="Get Value" onclick="alert($('#myselect').val())"/>
<input type="button" value="Get Text Value" onclick="alert($('#myselect option:selected').text())"/>
How do I compress my code?
Generally the best way to do it is to use Dean Edwards' Packer (this is the same script that jQuery uses to compress its copy of the library).
An alternative is to use Douglas Crockford's JSMin. This doesn't compress JavaScript code as small, but generally how you write your code matters less. jQuery also provides a pre-minified version of jQuery for your convenience.
If compressing your JavaScript breaks it, try running the code through JSLint. This will detect minor errors that can cause packed JavaScript to fail where the unpacked version works fine.
How do I submit a bug report?
You can submit a bug report through the jQuery bug tracker.
Any information you can provide will help, such as:
- A detailed bug report,
- An online demo page, showing the problem,
- A specific piece of code that is affected, or
- A pointer to the area in jQuery where the bug occurs.
The more information a bug report has, the more likely it will be to get fixed. If a long period of time has gone by without an update to your bug, please bring it up for discussion on the jQuery Dev List.
Why do ... ?
Why do my events stop working after an Ajax request?
Frequently, when you've added a click (or other event) handler to all links using $('a').click(fn) you'll find that the events no longer work after you've loaded new content into a page using an Ajax request.
When you call $('a') it returns all the links on the page at the time and .click(fn) adds your handler to each individual element. When new links are added, they are unaffected. See the AJAX and Events Tutorial for longer discussion.
You have two ways of handling this:
Re-binding
This method implicates calling the method .bind() on the new added elements, as they are loaded/added. For example:
$('a').click(fn);
$('#mydiv').load('my.html',function(){
$('a').click(fn);
});
Beware not to bind on the same element/s over and over, or the function will be executed many times on each click (or any other event).
Use the Live Query Plugin
Take a look at the Live Query plugin, by Brandon Aaron. It allows you to write something like this:
$('a').livequery('click',fn);
$('#mydiv').load('my.html');
The Live Query plugin automatically re-binds events to their target, even after you've loaded content in from a remote page.
Use Event Delegation
Event Delegation is a technique upheld by Event Bubbling. To handle events that bubble this way, you bind to a common container, and passively listen for events from there.
$('#mydiv').click(function(e){
if( $(e.target).is('a') )
fn.call(e.target,e);
});
$('#mydiv').load('my.html');
Plugins for event delegation
Intercept, by Ariel Flesler, accepts any valid selector, and also a collection of selector/function.
$('#mydiv').intercept('click', 'a', fn);
$('#mydiv').load('my.html');
Listen, also by Ariel Flesler, can scale much better than its counterparts, it is able to handle large amounts of selectors with nearly no additional overhead. The downside is, that it only supports 4 kind of selectors.
$('#mydiv').listen('click', 'a', fn);
$('#mydiv').load('my.html');
If you want to read further: check out this great article by Karl Swedberg.
Why doesn't an event work on a new element I've created?
As explained in the previous question about Ajax, events are bound only to elements that exist when you issue the jQuery call. When you create a new element, you must rebind the event to it.
You can avoid this extra step by using the Live Query plugin, as explained in the previous question about Ajax.
Why do animations set the display style to block?
To start with, you need to remember that only block-style elements can have a custom width or height. When you do an animation on an element that animates the height or width (such as show, hide, slideUp, or slideDown) then the display style property will be set to 'block' for the duration of the animation. The display property will be reverted to its original value after the animation completes.
There are two common workarounds:
If you want to have the element stay inline, but you just want it to animate in or out, you can use the fadeIn or fadeOut animations - which only affect the opacity of an element (and thus, don't need to have its display changed).
// Instead of this:
$("span").show("slow");
// do this:
$("span").fadeIn("slow");
The other option is to use a block-level element, but to add a float such that it appears to stay inline with the rest of the content around it. The result might looks something like this:
// A floated block element
<div style="float:left;">...</div>
// Your code:
$("div").show("slow");
When will...?
When will jQuery 1.2.4 be released?
jQuery 1.2.4 will be released TBD.
When will jQuery UI 1.5 be released?
jQuery UI v1.5 will be released around April/May, 2008.
Cookbook
Recipe: Simple menu with hover to show sub-menu items
Recipe: Hide All divs Except One
- See Hide All Except One (like tabs)
- Simple markup, 13 lines, unobtrusive, bookmarkable.