JOOMLA FICTION LAB
(3 votes)

How to use the jQuery no-conflict mode

Thursday, 11 August 2011 12:07
Mootools and jQuery can be used to create amazing stuff in your website. But what happens when you need to use both of them at the same time ?

First of all, it must be made clear that Mootools and jQuery can work together flawlesly. Mootools is prototype-base but jQuery is not, so they can work on the same page without any issues.

According to the jQuery documentation (http://docs.jquery.com/)

The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, "global" objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library (like Prototype, MooTools, or YUI)..

jQuery no-coflict mode


Although jQuery uses "$" as a shortcut for "jQuery" you can override that by calling jQuery.noConflict() at any point after jQuery and the Mootools library have both loaded.

Example 1

<html>
 <head>
   <script src="mootools.js"></script>
   <script src="jquery.js"></script>
   <script>
     jQuery.noConflict();
     
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });
     
     // Use Mootools with $(...), etc.
     $('an_id').hide();
   </script>
 </head>
 <body></body>
 </html>

Example 2

If you prefer to use a short name instead of jQuery, you can do this:
<html>
 <head>
   <script src="mootools.js"></script>
   <script src="jquery.js"></script>
   <script>
     var $j = jQuery.noConflict();
     
     // Use jQuery via $j(...)
     $j(document).ready(function(){
       $j("div").hide();
     });
     
     // Use Mootools with $(...), etc.
     $('an_id').hide();
   </script>
 </head>
 <body></body>
 </html>

Example 3

If you want to modify a jQuery script to use the no-conflict mode, follow this example:

ORIGINAL SCRIPT Example

$(document).ready(function(){								
 $('#id').click(function () {
 //Your code here		
 });	
});										

MODIFIED NO-CONFLICT SCRIPT Example

jQuery.noConflict();					
jQuery(document).ready(function(){								
 jQuery('#id').click(function () {
 //Your code here - Use jQuery instead of $	
 });	
});										





Add comment


Security code
Refresh