$ versus jQuery

Why would that be the case? Is his $/jQuery distinction correct?

Because almost every JavaScript library defines a function called $. When you have many libraries in one document, conflicts may appear. If you are sure that jQuery is and always will be the only script defining that function, I wouldn’t have anything against using $.

jQuery defines a nice solution to resolve conflicts: jQuery.noConflict. By using this function you can define your own name, whereby jQuery will be accessible, e.g.

var $jq = jQuery.noConflict(true);

Calling this function will result in restoring previous values for $ and jQuery variables when existed before initializing jQuery. I don’t remember if any other libraries try to resolve name conflicts.

If you want to use $ instead of jQuery all the time you can run your code in a separate, private scope that holds the definition of $ by using a self-invoking function.

(function($){
   // your code goes here
   $("body").append("<p>Hello World!</p>");
})(jQuery); // or even jQuery.noConflict()

Leave a Comment