Home > Frameworks, IT, JavaScript > jQuery conflicting with other libraries, solution

jQuery conflicting with other libraries, solution

jQuery logo

What if you already use some library that occupies the $ variable and you want to continue using it and jQuery together.  What happens in this case if you load jQuery is that it will override the variable to jQuery object and you won’t be able to use your existing library. Possible solutions of this are:

  • Reassign jQuery from $ to something like $jq.
  • Include jQuery first and after it the other library. After this instead of typing $ you will have to type jQuery. Example:  jQuery(‘#mydivId’);
  • You can also use the jQuery.noConflict() method to revert the $ to the value it had before jQuery was included in the page.

To me the 3rd option seems the best of all. This way you don’t have to worry about anything at all. Here’s a small example of it’s implementation taken from jQuery documentation:

<html>
 <head>
   <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 $(...), even though you've loaded jQuery after loading prototype
     $('someid').hide();
   </script>
 </head>
 <body></body>
 </html>

This is in my opinion the cleanest solution to the issue.  Also if you use jQuery plugins load them before calling the jQuery.noConflict() method.

For more information see:

jQuery Documentation: Integration with other Libraries

Share and Enjoy:
  • StumbleUpon
  • Twitter
  • Facebook
  • MySpace
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Technorati
  1. No comments yet.
  1. No trackbacks yet.