Aliases for jQuery Namespace

There can be cases when you are using jQuery together with other JavaScript library or libraries. Like jQuery, many other JavaScript libraries also use the $ as a function or variable name. On such instances, it is advised to use the $.noConflict() method to eliminate any namespace conflicts. So, the $.noConflict makes $ available for other libraries; while in jQuery, jQuery can be used as alias for $.

<script type="text/javascript" src="otherLib.js</script>
<script type="text/javascript" src="jquery.js"</script>
&lt;script type="text/javascript"&gt;<br /><br />$.noConflict();<br /><br />// Other library's $ code here.<br /><br />&lt;/script&gt;

Thus, the .noConflict() method adds the ability to replace $ with another alias. Additionally, it also allows you to define a custom namespace/alias for the jQuery object. Suppose you are writing a project for any company ABC, then it would be good to use ABC('contentArea').show() instead of jQuery('contentArea').show() or $('contentArea').show().

Continue to Use $ with jQuery code

However, if you have already written jQuery code and some new library started to conflict with jQuery code. You might not want to change the functional jQuery code. In this case, there is a way for continuing to use $ alias with jQuery as well as any other library. The handler of the .ready() method can take $ as a parameter. Since, this parameter gets passed to the global jQuery object, so we can continue to use the $ within the scope of .ready() handler.

jQuery(document).ready(function($) {<br /><br />// continue to use $ in the code.<br /><br />});

The shorthand equivalent for the above syntax can also be used.

jQuery(function($){<br /><br />// continue to use $ in the code.<br /><br />});

We read about similar example of aliasing in the post about jQuery’s document ready event.  Here, a complete sample code for above example can be

&lt;script type="text/javascript" src="otherLib.js"&gt;&lt;/script&gt;<br /><br />&lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt;<br /><br />&lt;script type="text/javascript"&gt;<br /><br />$.noConflict();<br /><br />jQuery(function($) {<br /><br />// jQuery code with $.<br /><br />});<br /><br />// Other library's $ code here.<br /><br />&lt;/script&gt; 

To further make it shorter, the $.noConflict() function can also be chained with the .ready() function.

$.noConflict()(function(){<br /><br />// jQuery code<br /><br />});<br /><br />// Other library's $ code here.<br /><br />

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>