When using other JavaScript frameworks on your site along with jQuery, there is the potential for a conflict to happen, where multiple frameworks try to run the same block of code.
The following shows a typical line of jQuery. What makes the browser realize it’s dealing with something that is NOT plain JavaScript, is the $. This tells the browser to use jQuery.
$('p').hide()
However, there are other JavaScript frameworks/libraries that use the $, and if you are using multiple libraries that do so, there may (probably will) be a conflict.
Writing Out jQuery Instead of Using $
One way to overcome any conflicts with other libraries is to write out jQuery instead of using the $ sign.
jQuery('p').hide()
Here’s what it looks like in a typical block of jQuery code. This will avoid any conflicts.
jQuery(document).ready(function() {
jQuery('button').click(function() {
jQuery('p').hide();
});
});
The noConflict() Method
Another (maybe better) way to avoid the conflict is to use the noConflict() method built into jQuery to assign a different string to notify the browser that jQuery is being used. In the following, “jq” is assigned to represent the default $ sign.
var jq = $.noConflict();
jq(document).ready(function() {
jq('button').click(function() {
jq('p').hide();
});
});
Note
Using the noConflict method, any string can be assigned to represent the $ in jQuery.
var xx = $.noConflict(); var Pete = $.noConflict(); var whatever = $.noConflict();
With all this said, it is unlikely that you’ll have a conflict and need to use anything other than the default $ sign. Most often, you don’t use numerous JavaScript frameworks, as that would be unnecessary and would contain a lot of redundant methods. Plus, it slows down the site.