How to avoid conflict between jQuery and Mootools

7

What good practices to avoid conflicts between the jQuery and Mootools libraries?

This example gives the error Uncaught TypeError: Object [object Object] has no method 'fade'

//codigo Mootools
$('sobreCamada').fade('in');

//codigo jQuery
setTimeout(function () {
    $('#sobreCamada').fadeIn().delay(1000).fadeOut(function () {
        $(this).remove()
    });
}, 2000);
    
asked by anonymous 21.12.2013 / 00:46

2 answers

10

Since both Mootools , jQuery (and even Prototype ) use the dollar $ the dollar is the problem that has to be solved and the source of conflict between the two libraries.

Mootools uses $() to select elements by ID. So the Mootools% code with% is similar to the% jQuery method with%. Mootools has an alternative to select an element by ID, using $('meuId')

Different options:

  • Scripts loading order:

Mootools detects whether the $('#meuId') dollar is already in use and does not re-declare the document.id('meuId'); function, so if Mootools is the last to load the problem should disappear. In this case you should use $ in Mootools instead of $() ;

  • document.id()

jQuery has a method to free the dollar and enter non-conflict mode >. In practice it is even possible to use $() and hence call jQuery by jQuery.noConflict() instead of var jQ = jQuery.noConflict(); or jQ() . The most common is to use $() instead of jQuery() , as is the case of Wordpress that loads jQuery in non-conflict mode.

  • jQuery()

Another option is to change the scope of the dollar. Passing the dollar as a parameter for an anonymous function, this solution is practical to package existing code without having to change all $() to (function($){/*...*/})(jQuery) . This variant also needs the $ statement.

    
21.12.2013 / 00:46
3

To avoid conflict between these libraries you can create a closure and limit the variables created and defined to a certain scope

To do this in JavaScript we use functions

function criarClosure(){
    //Aqui está definido um closure
    //E todas as variáveis estão limitadas ao escopo da função
}

So in the case of jQuery, you can create an anonymous function that already runs

(function($){
    //Utilização padrão do jQuery
    $(document).ready(function(){
        ...
    });
})(jQuery); //Nessa linha executamos a função definida sem conflitos

In the jQuery site there is more information about it

Avoiding Conflicts with Other Libraries

    
21.12.2013 / 15:11