jQuery noConflict() Method
The dollar sign $ is just a short name for the jQuery function. But other libraries (like Prototype or MooTools in old projects) also used $ for their own function. If both are loaded on one page, they fight for the name.
The method jQuery.noConflict() gives the $ back to the other library, and you use jQuery with the long name jQuery or a new short name.
How to use it
<script src="other-library.js"></script> <!-- this library uses $ -->
<script src="jquery-3.7.1.min.js"></script> <!-- jQuery is loaded after it -->
<script>
jQuery.noConflict(); // give the $ back to the other library
jQuery(document).ready(function () {
jQuery('p').text('Hello');
});
</script>
Example run
<p id="msg">Old</p>
console.log('before: $ is ' + typeof $);
jQuery.noConflict();
console.log('after: $ is ' + typeof window.$);
jQuery('#msg').text('Changed with jQuery');
console.log(jQuery('#msg').text());
before: $ is function
after: $ is undefined
Changed with jQuery
After noConflict(), the name $ is free. In this test there was no other library, so it became undefined. In a real page with another library, the $ goes back to it.
Your own short name
The method returns jQuery, so you can save it in a variable with any name:
var $j = jQuery.noConflict();
$j('#msg').addClass('done');
console.log($j('#msg').attr('class'));
done
Use $ inside a function
A nice way is to pass jQuery as an argument to a function, and name the argument $. Inside the function the $ is always jQuery.
jQuery.noConflict();
jQuery(document).ready(function ($) {
// $ means jQuery only inside this function
$('#msg').text('Inside ready: ' + typeof $);
});
(function ($) {
$('#msg').addClass('wrapped');
})(jQuery);
setTimeout(function () { console.log(jQuery('#msg').text() + ' | ' + jQuery('#msg').attr('class')); }, 50);
Inside ready: function | wrapped
The second pattern, an immediately invoked function with jQuery as the argument, is the way used by most plugins and WordPress code.
WordPress
WordPress loads its own jQuery in “no conflict” mode. The $ is not available by default, so in WordPress scripts you write jQuery(...) or use the wrapper function above.
jQuery(document).ready(function ($) {
$('.menu-toggle').on('click', function () {
$('#menu').slideToggle();
});
});
noConflict(true)
If another version of jQuery was loaded before, jQuery.noConflict(true) gives back also the name jQuery to the old version. This is used when two versions of jQuery must stay on the same page. Try to avoid it, because it makes the page heavy.
| Exercises & Assignments |
|---|
| No Content Found. |