The
noConflict()
is an inbuilt function in jQuery and jQuery generally use "$" sign as a shortcut identifier. There are many javascript libraries like Angular Js, Ember, Knockout and more. Now if other JavaScript frameworks with jQuery start using "$" sign as a shortcut, then there will be a conflict and one of the framework may stop working. Therefore, noConflict method is implemented.
Syntax:
$.noConflict();
Parameters:
It does not accept any parameter.
Return Value:
It does not return anything.
How conflict arises?
Example:
src="prototype.js"
src="jquery.js"
In above example, there are two JavaScript libraries used in same file and both of them using same “$” sign to select elements. Now the conflict arise and may one of the libraries fails to access the element using “$” sign. The noConflict() method releases the hold on the "$" shortcut identifier, so that other scripts can use it.
jQuery code which produces conflict:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/
jquery/3.3.1/jquery.min.js"></script>
<script>
jq(document).ready(function() {
jq("button").click(function() {
jq("p").text("jQuery is still working!");
});
});
</script>
</head>
<body>
<p style="color:green">This will show how to save
reference and use them.</p>
<button>Click Me.!</button>
</body>
</html>
Output:
Before clicking on the button-
After clicking on the button--
Here output is same before and after clicking the button and hence there is existence of conflict.
jQuery code to overcome such conflict using noConflict() function:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//Here noConflict() reference is saved to a variable
var jq = $.noConflict();
jq(document).ready(function() {
jq("button").click(function() {
jq("p").text("jQuery is still working!");
});
});
</script>
</head>
<body>
<p style="color:green">This will show how to save
reference and use them.</p>
<button>Click Me.!</button>
</body>
</html>
Output:
Before clicking the button-
After clicking the button-