Ryan Michela
Ryan Michela

Reputation: 8374

Conflict between jQuery, Prototype, and plugins

I am trying to deconflict Prototype and jQuery in a rails app. I discovered that jQuery broke Prototype a good way into the app.

I started the process by adding $jq = jQuery.noConflict(); to the application.js file.

I then began going through all the .erb and .js files in the project, looking for jQuery calls to $ and replacing them with $jq. Then I got to some of the jQuery plugin files.

Do I have to convert all $ references to $jq in the jQuery plugin .js files?

Upvotes: 0

Views: 1383

Answers (5)

Vlasar
Vlasar

Reputation: 21

I came across this problem today and wrapping plugin code like:

(function($) {
  //plugin code
})(jQuery);

didn't work until I moved the line which includes prototype library files before the line which includes jQuery library files.

Upvotes: 2

Drew Wills
Drew Wills

Reputation: 8446

Try loading jQuery and all its plugins together, in a sequence, and then call noConflict(). Here's an example:

<script src="/path/to/1.3.1/jquery-1.3.1.min.js" type="text/javascript"></script>
<script src="/path/to/1.3.1/jquery-ui-1.6rc6.min.js" type="text/javascript"></script>
<script src="/path/to/jquery/plugin.js" type="text/javascript"></script>
<script type="text/javascript">
    var $jq = $jq || {};
    $jq.jQuery = jQuery.noConflict(true);
</script>

Then later in your own code you can reference jQ -- complete with the plugins you desire -- using the $jq.jQuery variable.

Upvotes: 0

Powerlord
Powerlord

Reputation: 88806

Do I have to convert all $ references to $jq in the jQuery plugin .js files?

Generally, no. Most plugins are set to pass the jQuery object in as $. You can tell if a plugin does this, because it'll look like this:

(function($) {

// Actual plugin code

})(jQuery);

Upvotes: 1

Simon
Simon

Reputation: 37978

Or you could wrap them in a closure

(function($){

// add old jQuery code here.

})($jq);

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30520

Have you considered adding it to the prototype library js file? That way, whenever prototype is loaded it automatically deconflicts jquery.

We have done a similar thing here with mootools.

In answer to your question, if the plugin has been written correctly, then you shouldn't have to change this there. The following convention should wrap the plugin, ensuring correct operation even when noconflict has been turned on.

;(function($) {

//plugin code

})(jQuery);

Upvotes: 1

Related Questions