How to Release $ Variable Using jQuery noConflict

By default, jQuery assigns the global shortcut $ to itself, which frequently causes naming collisions when used alongside other JavaScript libraries such as Prototype, MooTools, or AngularJS that also rely on $. To prevent these conflicts, jQuery provides the built-in jQuery.noConflict() method. Calling this function relinquishes jQuery's control over the $ identifier, restoring it to whatever library held it before jQuery was loaded, ensuring seamless interoperability in multi-library environments.

The Basic noConflict() Implementation

To return control of the $ variable immediately, call noConflict() after loading jQuery and before executing scripts that depend on the other library.

// Release the $ symbol
jQuery.noConflict();

// $ now belongs to the other library (e.g., Prototype)
$('someElement').hide();

// jQuery is still available through the full 'jQuery' namespace
jQuery('#anotherElement').hide();

Assigning jQuery to a Custom Shortcut

If you still want a concise shortcut for jQuery without using $, you can assign the return value of jQuery.noConflict() to a custom variable.

// Assign jQuery to a custom alias
var $j = jQuery.noConflict();

// Use the new alias for jQuery
$j('#myElement').fadeIn();

// Use $ for the other library
$('#otherElement').show();

Using $ Safely Within a Local Scope

You can release the global $ while still using $ inside your jQuery scripts by wrapping your code in an Immediately Invoked Function Expression (IIFE) or using jQuery's ready event wrapper.

Method 1: Using an IIFE

jQuery.noConflict();

(function($) {
    // $ refers to jQuery only within this block
    $('#myDiv').addClass('active');
})(jQuery);

// $ outside this block belongs to the other library

Method 2: Using the Ready Handler

jQuery.noConflict();

jQuery(document).ready(function($) {
    // $ is locally scoped to jQuery inside this callback
    $('button').click(function() {
        $('p').toggle();
    });
});

Complete Namespace Release

If you need to release both the $ variable and the jQuery global variable entirely, pass true as an argument to the method.

// Releases both $ and jQuery from the global scope
var domHelper = jQuery.noConflict(true);

// Access jQuery through your designated variable only
domHelper('#container').text('Hello World');