Most JavaScript frameworks use the $ sign as a shortcut. If you use jQuery
alongside another framework (like Prototype, MooTools, or YUI) that also uses the
$ sign, your scripts will crash due to a naming collision. The
noConflict() method solves this by releasing jQuery's hold on the
$ shortcut.
Once you call $.noConflict(), the dollar sign is given back to the other
library. To use jQuery elements, you must use the full jQuery keyword
instead.
$.noConflict();
// Now you MUST use jQuery name
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery is still working!");
});
});
If you find jQuery too long to type, the noConflict() method
returns a reference to the jQuery object, which you can assign to a new, unique variable
name.
var jq = $.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("Custom shortcut is working!");
});
});
If you have thousands of lines of code using $ and you don't want to change
them all, you can pass the $ sign as an argument to the ready()
function. This makes it valid **only** inside that specific block of code.
$.noConflict();
jQuery(document).ready(function($) {
// $ is safe to use as jQuery INSIDE this block
$("button").click(function() {
$("p").text("Safe block works perfectly!");
});
});
// $ is NOT valid here (reverts to other framework)
$ sign is just a variable name. In
JavaScript, the last script to load "wins" the variable. noConflict()
manually resets the variable to its previous state.
noConflict() is essential for working
with CMS platforms like WordPress or Drupal.
$ shortcut.$ to jQuery(document).ready() is the cleanest way
to maintain standard syntax.