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.

Ovais is a storage architect with keen focus on reliability, efficiency and performance of OLTP databases, more specifically MySQL. He currently works at Uber on ensuring storage reliability and scalability. Previously, he helped different web properties scale their MySQL infrastructure. He also worked at Percona as a Senior MySQL consultant and at a few other startups in various capacities.