jQuery – Using $ with other JavaScript libraries

Although $ sounds native to jQuery alone, but there are other JavaScript libraries and frameworks as well that use $, one example is scriptaculous.

But what if you want to use $ in your jQuery based code or plugin, $ sure is a very short shortcut.

I will show you a nice little trick of how to do so.
The trick involves writing all the code in a function and executing that function immediately:

(function()
{
  // put your code here
})();

See how the function gets executed immediately, so all you need to do now to use $, is have the input parameter of this function named $ and pass in the jQuery object using the keyword jQuery.

The example follows:

(function($) // $ is the parameter that is passed the jQuery object
{
  
  // put your code here
  $( '.show-me' ).fadeIn( 'fast' );
  $( '#editor' ).load( 'some-url.php' );
  
  // add more code
  
  // define some variables
  // these variables are only available within this function
  var count = 1;
  var props = {};
  
  // define some methods
  function sum( num1, num2 )
  {
    return num1 + num2;
  }
  
  // use your methods
  $( '#show-sum' ).text( sum( 2, 3 ) );
  
})(jQuery); // pass the jQuery object and execute the function immediately

Thanks to this nice little trick I have been using the $ shortcut in my code, with out any concerns of conflict.