How to Use jQuery with Other Libraries Using the $ Symbol
Yes, jQuery can easily be used alongside other JavaScript libraries
that also use the $ symbol, such as Prototype, MooTools, or
Backbone. Because the dollar sign is simply a JavaScript identifier,
multiple libraries attempting to use it as a global shortcut will
overwrite each other. jQuery provides a built-in mechanism called
jQuery.noConflict() specifically designed to resolve this
issue and prevent namespace collisions.
Why the Conflict Occurs
When you load multiple libraries that define the
window.$ variable, whichever library loads last takes
ownership of $. If jQuery is loaded after another library
that uses $, the original library loses its shortcut,
breaking scripts that depend on it.
Resolving Conflicts
with jQuery.noConflict()
Calling jQuery.noConflict() relinquishes jQuery's
control over the $ shortcut, returning control to whichever
library had it previously. After calling this method, you can continue
interacting with jQuery in several ways.
1. Use the
jQuery Global Name Directly
Once you invoke noConflict(), the $ symbol
is freed up, but the global jQuery identifier remains fully
functional.
jQuery.noConflict();
// Prototype or another library owns $
$('otherLibraryElement').hide();
// jQuery uses its full name
jQuery('#myElement').fadeIn();2. Create a Custom Alias
You can assign the return value of jQuery.noConflict()
to a custom variable, allowing you to use a custom shortcut instead of
the full jQuery name.
const $j = jQuery.noConflict();
// Use $ for the other library
$('element-id').addClassName('active');
// Use $j for jQuery
$j('#element-id').addClass('active');3. Scope the $ Symbol
Locally
If you prefer to continue writing standard jQuery code using the
$ alias without polluting the global scope, you can pass
jQuery into a self-executing anonymous function (IIFE) or
map it through the standard document-ready wrapper.
Using an Immediately Invoked Function Expression (IIFE):
jQuery.noConflict();
(function($) {
// $ refers strictly to jQuery inside this block
$('#myDiv').text('Hello World');
})(jQuery);
// Outside the block, $ belongs to the other libraryUsing the Document Ready Handler:
jQuery.noConflict();
jQuery(document).ready(function($) {
// $ refers to jQuery inside this function
$('p').css('color', 'blue');
});Using these methods ensures that jQuery and any other library relying
on the $ variable can run concurrently on the same webpage
without errors.