Martti Laine
Martti Laine

Reputation: 12985

jQuery(selector) or $(selector), which one?

Which is better way to use jQuery()? I've heard that jQuery(element) doesn't ruin code in e.g. Wordpress. But $ is easier and faster to write.

Which one do you prefer and why?

Upvotes: 2

Views: 289

Answers (6)

SoftwareGeek
SoftwareGeek

Reputation: 15772

You can use var jq=jQuery.noConflict(); to deal with name conflicts.

Ex:

var $jq=jQuery.noConflict();
$jq("p").hide();

Upvotes: 0

nickf
nickf

Reputation: 546005

Most of my jQuery code falls into two categories: plugins and on-page-load stuff.

For plugins, here's the easiest way:

(function($) {
    $.fn.myplugin = function() { ... };
})(jQuery);

For on-page-load stuff, which is most of it, just do this:

jQuery(function($) {
    $('a[href$="foo"]').click( ... );
});

This way, it doesn't matter at all if there's extra libraries included (eg: Prototype), and you can still use $ instead of typing out "jQuery" each time.

Upvotes: 1

ndim
ndim

Reputation: 37767

For your own extensions that use $ only to call jQuery, you can also use the standard trick of wrapping your code like this

(function($) {
   ... your other code using $(selector).moo here ....
})(jQuery);

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532435

My order of preference is $(), then var $jq = jQuery.noConflict(); $jq(), then finally jQuery(). You can also limit the scope of the $ function by doing:

;(function($){
    ...in here $ means jQuery...
})(jQuery);

That is create an anonymous function with a parameter of $, pass in jQuery as the parameter and within the function the parameter scope overrides any globally scoped $ function. The latter is most useful when creating plugins yourself.

Upvotes: 10

user47322
user47322

Reputation:

It just depends on what you need to do, they're both identical.

If you're using another library like Prototype (which also uses $), you'll need to us jQuery, but in most cases where there is no clash, just use $()

Upvotes: 5

Rich
Rich

Reputation: 36806

The $ shorthand is also used by other frameworks (like prototype), so if you're not using that, feel free to use $ for shorthand. The two are just aliases of each other as far as I know.

Upvotes: 2

Related Questions