Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

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);

Or you could wrap them in a closure

(function($){

// add old jQuery code here.

})($jq);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top