Using jQuery $.noconflict to avoid conflicts with other javascript libraries

jQuery noconflict() method

As described in introduction chapters, jQuery is a javascript library that is built on “write less, do more” slogan. There are many other java script libraries out there for different purposes e.g. javascript MVC, Ember, MooTools and others.

What if you are using other libraries in your application along with jQuery and the other one also uses ‘$’ just like jQuery does? ‘$’ in jquery is alias or shorthand for jQuery as we also used in examples.

In order to avoid conflicts between different libraries using ‘$’ jQuery provides $.noConflict() method. The $.noConflict() method gives up the hold of using ‘$’ alias so it can be used for other libraries. In place of ‘$’ you can specify other alias to be used for shorthand instead of using ‘jQuery’. The examples below shows how, but first noconflict syntax.

jQuery noConflict syntax

jQuery.noConflict() or $.noConflict();

Example of using jQuery with noConflict();

In example below as you click button fadetoggle() method is used to fade in and fade out elements. The example uses ‘$’ alias in this example. Before document.ready we placed $.noConflict(); method and so the code will not work as ‘$’ is “disabled”. To run this properly you can disable or remove, and code will work.

Example using jQuery rather ‘$’

Now same example as used above and using jQuery in place of ‘$’ alias and then using $.noConflict(); method. See code below:

Using custom alias like your company/website name

Very interesting and cool feature is you can use your own alias rather ‘$’ or jQuery as shorthand. For example using website name or its abbreviation or company name. In example below we use tutorialscollection short name ‘tc’.

This line of code will make ‘tc’ as alias rather ‘$’.

var tc = $.noConflict();