This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

@Ben: The reason I avoid such idioms in JavaScript is because I don't want to give the illusion of someDiv having being scoped in the if statement, because it isn't; JavaScript only supports function scope
–
Andreas GrechMay 3 '10 at 15:55

I'm really not a fan of the $(document).ready(fn) shortcut. Sure it cuts down on the code but it also cuts way down on the readability of the code. When you see $(document).ready(...), you know what you're looking at. $(...) is used in far too many other ways to immediately make sense.

If you have multiple frameworks you can use jQuery.noConflict(); as you say, but you can also assign a different variable for it like this:

var $j = jQuery.noConflict();
$j("#myDiv").hide();

Very useful if you have several frameworks that can be boiled down to $x(...)-style calls.

@Oli: About the document ready-shorthand; you have a point. But never the less: it is a tip/trick. One which I use in all my code purely because I think it "looks" better. A matter of personal preference, I guess :)
–
roosteronacidOct 8 '08 at 13:19

html5 data attributes make this less of an issue; there is discussion afoot on bringing html5 data attribute inline with jquery's data() function: forum.jquery.com/topic/…
–
Oskar AustegardOct 14 '10 at 3:05

10

@Oskar - yep this has been implemented in jQuery 1.4.3 -- data-* attributes are automatically available via calls to .data()
–
nickfOct 16 '10 at 21:07

UPDATE2: live() has been long deprecated, even before jQuery 1.7. For versions jQuery 1.4.2+ before 1.7 use delegate() and undelegate(). The live() example ($('button.someClass').live('click', someFunction);) can be rewritten using delegate() like that: $(document).delegate('button.someClass', 'click', someFunction);.

Replace anonymous functions with named functions. This really supercedes the jQuery context, but it comes into play more it seems like when using jQuery, due to its reliance on callback functions. The problems I have with inline anonymous functions, are that they are harder to debug (much easier to look at a callstack with distinctly-named functions, instead 6 levels of "anonymous"), and also the fact that multiple anonymous functions within the same jQuery-chain can become unwieldy to read and/or maintain. Additionally, anonymous functions are typically not re-used; on the other hand, declaring named functions encourages me to write code that is more likely to be re-used.

I'm sorry Ben, but I fail to see how your comment has any relevance to my post. Can you elaborate? You can still use 'self' (or any other variable) using my suggestion; it won't change any of that at all.
–
kenJun 1 '09 at 16:44

2

I must mention: always fur variable and functions in namespace not in root !!
–
jmavOct 27 '09 at 23:17

There is a difference though, the first example will wait for the document.ready() event to fire, while the second won't.
–
SamBeranFeb 11 '09 at 2:40

1

@SamBeran: True, the second example will run immediately; however, if you are wrapping an object-literal, you can use $(document).ready(...) inside the object-literal which means you can specify when you'd like to run each piece of code.
–
wilmooreOct 16 '10 at 7:01

4

instanceOf won't work, only instanceof. And it won't work anyway, because jQuery instanceof jQuery will return false. $ == jQuery is the correct way to do it.
–
nyuszika7hFeb 15 '11 at 15:34

On the core jQuery function, specify the context parameter in addition to the selector parameter. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.

Example: Finds all inputs of type radio within the first form in the document.

A note: $(document.forms[0]).find('input:radio') does the same thing. If you look at the jQuery source, you'll see: if you pass a second parameter to $, it will actually call .find().
–
nyuszika7hFeb 15 '11 at 16:07

If you have really complex documents where running the jquery each() function locks up the browser during the iteration, and/or Internet Explorer pops up the 'do you want to continue running this script' message, this solution will save the day.

it better to put the $(this) reference in a local variable, because you wil take a minor perfomance hit here, because it will take a little longer...
–
Sander VersluysJul 9 '09 at 11:51

4

In this case (no pun intended) I am only using "this" one time. No need for caching.
–
roosteronacidJul 15 '09 at 7:26

1

A small tip. While it may not matter in this case it's always a bad idea to make extra changes to the DOM. Say for example the element you are hovering over already had the class "hover". You would be removing this class and re-adding it. You can get around that with $(this).siblings().removeClass("hover"). I know this sounds like such a small thing but every time you change the DOM another browser redraw may be triggered. Other possibilities include events attached to DOMAttrModified or the classes changing the height of the element which could fire other "resize" event listeners.
–
gradbotApr 30 '11 at 16:38

1

If you want to use the cache and minimize DOM changes you can do this. cache.not(this).removeClass("hover")
–
gradbotApr 30 '11 at 16:47

As a more complex example, say you've got a list of foods in a store, and you want to show only the ones that match a user's criteria. You have a form with checkboxes, each one containing a criteria. The checkboxes have names like organic and lowfat, and the products have corresponding classes - .organic, etc.

var $allFoods, $matchingFoods;
$allFoods = $('div.food');

Now you can keep working with that jQuery object. Every time a checkbox is clicked (to check or uncheck), start from the master list of foods and filter down based on the checked boxes:

// Whenever a checkbox in the form is clicked (to check or uncheck)...
$someForm.find('input:checkbox').click(function(){
// Start out assuming all foods should be showing
// (in case a checkbox was just unchecked)
var $matchingFoods = $allFoods;
// Go through all the checked boxes and keep only the foods with
// a matching class
this.closest('form').find("input:checked").each(function() {
$matchingFoods = $matchingFoods.filter("." + $(this).attr("name"));
});
// Hide any foods that don't match the criteria
$allFoods.not($matchingFoods).hide();
});

It seems that most of the interesting and important tips have been already mentioned, so this one is just a little addition.

The little tip is the jQuery.each(object, callback) function. Everybody is probably using the jQuery.each(callback) function to iterate over the jQuery object itself because it is natural. The jQuery.each(object, callback) utility function iterates over objects and arrays. For a long time, I somehow did not see what it could be for apart from a different syntax (I don’t mind writing all fashioned loops), and I’m a bit ashamed that I realized its main strength only recently.

The thing is that since the body of the loop in jQuery.each(object, callback) is a function, you get a new scope every time in the loop which is especially convenient when you create closures in the loop.

Now, when you invoke the functions in the functions array, you will get three times alert with the content undefined which is most likely not what you wanted. The problem is that there is just one variable i, and all three closures refer to it. When the loop finishes, the final value of i is 3, and someArrary[3] is undefined. You could work around it by calling another function which would create the closure for you. Or you use the jQuery utility which it will basically do it for you:

Not that many use-cases for this. Never the less; I think it's neat :)

Update

Just in case you are not the comment-reading-type, ThiefMaster points out that the toggleClass accepts a boolean value, which determines if a class should be added or removed. So as far as my example code above goes, this would be the best approach...

Just include this script on the site and you’ll get a Firebug console that pops up for debugging in any browser. Not quite as full featured but it’s still pretty helpful! Remember to remove it when you are done.

The "console.info" of firebug, which you can use to dump messages and variables to the screen without having to use alert boxes. "console.time" allows you to easily set up a timer to wrap a bunch of code and see how long it takes.

I ran into this issue when I was trying to change the type of an input element already attached to the DOM. You have to clone the existing element, insert it before the old element, and then delete the old element. Otherwise it doesn't work:

The data function has been mentioned before. With it, you are able to associate data with DOM elements.

Recently the jQuery team has added support for HTML5 custom data-* attributes. And as if that wasn't enough; they've force-fed the data function with steroids, which means that you are able to store complex objects in the form of JSON, directly in your markup.