jQuery | noConflict() with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
                  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>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <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>

chevron_right


Output:
Before clicking the button-

After clicking the button-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.