views:

147

answers:

6

Hello

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?

Martti Laine

+2  A: 

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.

Rich
Argh, ninja'd :p
Charlie Somerville
+5  A: 

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 $()

Charlie Somerville
Thanks for both answers, this one was a bit faster, though :-D
Martti Laine
+1  A: 

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);
ndim
+9  A: 

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.

tvanfosson
+1  A: 

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.

nickf
A: 

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

Ex:

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