Getting jQuery and Prototype to work together in Rails

I wasted a couple of hours yesterday trying to get drag and drop to work in Rails using Prototype. I was following the example from Railscasts so I knew it should work. After some troubleshooting I finally figured out that it is because I am also using JQuery in the project as well.

Below is a quote from the JQuery site. They say jQuery should work with Prototype and then in the next sentence lists a caveat. Well…it just so happens the mentioned caveat is what was causing my problems.

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

That said, there is one caveat: By default, jQuery uses “$” as a shortcut for “jQuery”

They also list several options on how to solve the problem. Because I wasn’t using jQuery and Prototype on the same page I was able to use a provided jQuery method jQuery.noConflict() which ensures that “$” object will not conflict with other libraries.

The following code snippet shows how to use the method.

<!-- Added so prototype and JQuery play well together -->
<script type="text/javascript">

Keep in mind that this only works if you are aren’t usingĀ  jQuery and Prototype on the same page. If you are using jQuery and Prototype on the same page then you will need to use one of the solutions provided by jQuery.