jQuery - jQuery noConflict()?
jQuery noConflict()
The jQuery.noConflict()
method is used when you want to avoid conflicts between jQuery and other JavaScript libraries that also use the $
symbol (like Prototype, MooTools, or AngularJS).
It allows you to relinquish control of the $
variable so that other libraries can use it without issues, while you can still use jQuery with a different variable name.
1) Why Use noConflict()
-
By default, jQuery uses
$
as a shorthand forjQuery
. -
But if another library also uses
$
, a conflict can occur. -
To avoid this,
jQuery.noConflict()
lets you safely assign jQuery to another variable.
2) Syntax
jQuery.noConflict();
After calling it, the $
shortcut is released, and you must use jQuery
instead:
jQuery(document).ready(function() {
jQuery("p").text("jQuery is working!");
});
3) Using noConflict()
with a Custom Variable
You can assign jQuery to a custom variable and continue using $
for other libraries.
Example
var jq = jQuery.noConflict();
jq(document).ready(function() {
jq("p").css("color", "green");
});
-
Here,
jq
replaces$
for jQuery. -
$
can now safely be used by another library.
4) Using $
Inside a Local Scope
Even after calling noConflict()
, you can still use $
inside a function by passing it as a parameter:
jQuery.noConflict();
(function($) {
$(document).ready(function() {
$("h1").css("color", "blue");
});
})(jQuery);
-
Inside the IIFE (Immediately Invoked Function Expression),
$
is locally mapped tojQuery
. -
Outside the function,
$
is free for other libraries.
5) Full Example with Two Libraries
Without noConflict()
→ Problem
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("p").css("color", "red"); // ERROR: Conflict with Prototype
});
</script>
-
Both Prototype and jQuery use
$
. -
This causes unexpected errors.
With noConflict()
→ Solution
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var jq = jQuery.noConflict();
jq(document).ready(function() {
jq("p").css("color", "red"); // Works fine
});
</script>
-
Now,
$
belongs to Prototype. -
jQuery uses
jq
instead.
6) Advanced Usage: Returning $
Back to jQuery
If you want to temporarily release $
but reclaim it later:
jQuery.noConflict();
var jq = jQuery;
// Use jq for now
jq("div").hide();
// Later, reclaim $
$ = jq;
$("div").show();
7) Key Points to Remember
Aspect | Without noConflict() |
With noConflict() |
---|---|---|
$ variable |
Belongs to jQuery | Released for other libraries |
Usage of jQuery | $("p") |
jQuery("p") or custom var |
Conflict risk | High | Eliminated |
Ideal for | Projects with only jQuery | Projects using multiple libraries |
8) Summary
-
jQuery.noConflict()
is used to avoid conflicts when multiple libraries use$
. -
You can use:
-
jQuery
instead of$
-
Assign a custom variable like
var jq = jQuery.noConflict()
-
Use
$
safely inside local scopes.
-
-
Best practice when working with multiple frameworks on the same page.