There are a lot of different javascript libraries that commandeer the $ variable, like jQuery. $ is actually just a shorthand variable, which references jQuery. It's usually a good idea to free up $, to avoid possible conflicts with other includes trying to use it. Let's start off with some easy code for accomplishing this:

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
var $j = $;
$ = undefined;
</script>

We have now saved a reference to $ into $j, so that we can use $j for jQuery functionality. $j("p.myClass").removeClass("myClass"), for example. We've accomplished the basic goal, but we can do better.

A few of issues with our first attempt:

  • If $ was pointing at anything before jQuery used it (like another library), that reference has been lost.
  • In the case of juggling multiple versions of jQuery (not something I would recommend), the last imported version will overwrite the former's jQuery variable.
  • Just for the sake of best practices, we should use jQuery's built-in noConflict() function, in case they add additional handling in later releases.

Thankfully, when jQuery is imported, it saves a reference to any existing $ into a private variable, called _$. Calling jQuery.noConflict() will not only reset $, it will return it to its pre-jQuery value. Another nice bonus is that the noConflict() function returns a reference to jQuery object itself. This allows us to combine the two lines, into simply "var $j = $.noConflict();"

One last note, about the argument sent to noConflict(). It defaults to false, but you can pass a boolean value, which instructs jQuery whether to release jQuery. This is safe to do, as long as we remember to use our shorthand variable in ALL cases. $j is a substitute for any reference to the jQuery object, so "jQuery.parseJSON(jsonString);" can be written as "$j.parseJSON(jsonString);"

So, too many words later, we arrive at the final code snippet used on the site:

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict(true);
</script>