HomeCoding & Programming

Resolve conflicts with jQuery and other JavaScript libraries using jQuery.noConflict

Like Tweet Pin it Share Share Email

A problem that often occurs in web development is a conflict between your jQuery function and some other JavaScript library.

 

This is due to many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery’s case,$ is just an alias for jQuery, so all functionality is available without using $.

 

The following article is a short guide on how you can avoid or resolve conflicts with jQuery and other JavaScript libraries.

All you need to do is wrap your jQuery function in some jQuery noconflict tags.

If you wanted to hide a div on load you would normally use the following code


    $(document).ready(function() {
    $('#myDiv').hide();
    });

 

However, if you are using another JavaScript library, such as Prototype, you will find this code doesn't work. This is because Prototype also uses the dollar sign ($); this causes a conflict.

 

To prevent this, you just need to do is wrap the code in these tags.

    (function($){
    $(document).ready(function() {
    // Do awesome stuff...
    $('#myDiv').hide();
    });
    })(jQuery);

 

You will notice that your code now functions as you would like it to work.

You can also create a alias for jQuery.noConflict(); and can use it further in jQuery function as below.


    <script type="text/javascript" src="other_javascript_library.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $.noConflict();
    // Code that uses other javascript library's $ can follow here.
    </script>

    var jQ = jQuery.noConflict();
    // Do something with jQuery
    jQ("div p").hide();

    // Do something with another library's $()
    $("content").style.display = 'none';

 

Hope this will help.