What is jQuery.noConflict()

What is jQuery.noConflict()? Well, jQuery is popular because there are plenty of useful, simple and easy to use plugins. But while using jQuery plugins, sometimes we include other libraries like prototype, mootools, YUI etc. The problem comes when one or more other libraries are used with jQuery as they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().

How to use it?

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
When .noConflict() is called then jQuery returns $() to its previous owner and you will need to use jQuery() instead of shorthand $() function. In this case, "jQuery" will be used in rest of the code. You won't be able to take advantage of shorthand.

There is another option if you want to take advantage of shorthand.
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     var $j = jQuery.noConflict();
     // Use jQuery via jQuery(...)
     $j(document).ready(function(){
       $j("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
But you still love $() and don't want to lose it. So what to do? But there is a solution for this also.
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Put all your code in your document ready area
     jQuery(document).ready(function($){
       // Do jQuery stuff using $
       $("div").hide();
     });
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
What you need to do is in jQuery(document).ready() put function($) and now you use $ for your jQuery code.

Note: All the above examples are taken from here.

Feel free to contact me for any help related to jQuery. I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..