2

I am trying to make a Redmine plugin that uses jquery.

I get conflicts, when I add the following line in my view:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

Uncaught TypeError: Cannot call method 'hasChildNodes' of undefined
prototype.js:5734
Uncaught TypeError: Object [object Object] has no method 'dispatchEvent'
prototype.js:828
Uncaught TypeError: Object [object Object] has no method 'attachEvent'

The view is a hook.

If I remove the <script src=""> , it works, but then I have no jQuery to use.

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
user852689
  • 751
  • 1
  • 10
  • 21

1 Answers1

7

Looking at it, the prototype library is also loaded. Usually a library will automatically load into the global scope by assigning themselves to the $ variable.

To get jQuery working, just add $.noConflict(); after you load jQuery (see noConflict on the jQuery API). This unloads jQuery from $ and reassigns it to what it was before (prototype).

Then you access jQuery using the jQuery object and not the $ shortcut.

  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });

If you really wanted to use a shortcut variable (for example, $j), then you can assign it when doing the noConflict:

var $j = $.noConflict(); // Then use $j instead of $

Alternatively, you can create an anonymous function and assign jQuery to $ within it. This is only done within the scope of the function (so prototype is still $ outside of the scope):

(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);

All of these (and a few other examples) are shown on the noConflict page - so you might want to have a look there.

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46