Resolve conflicts with jQuery and other JavaScript libraries using jQuery.noConflict

A problem that often occurs in web development is a conflict between your jQuery function and some other JavaScript library.

 

This is due to many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery’s case,$ is just an alias for jQuery, so all functionality is available without using $.

 

The following article is a short guide on how you can avoid or resolve conflicts with jQuery and other JavaScript libraries.

All you need to do is wrap your jQuery function in some jQuery noconflict tags.

If you wanted to hide a div on load you would normally use the following code

[code lang="js"]
$(document).ready(function() {
$('#myDiv').hide();
});
[/code]

 

However, if you are using another JavaScript library, such as Prototype, you will find this code doesn't work. This is because Prototype also uses the dollar sign ($); this causes a conflict.

 

To prevent this, you just need to do is wrap the code in these tags.

[code lang="js"]
(function($){
$(document).ready(function() {
// Do awesome stuff...
$('#myDiv').hide();
});
})(jQuery);
[/code]

 

You will notice that your code now functions as you would like it to work.

You can also create a alias for jQuery.noConflict(); and can use it further in jQuery function as below.

[code lang="js"]
<script type="text/javascript" src="other_javascript_library.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
// Code that uses other javascript library's $ can follow here.
</script>

var jQ = jQuery.noConflict();
// Do something with jQuery
jQ("div p").hide();

// Do something with another library's $()
$("content").style.display = 'none';
[/code]

 

Hope this will help.