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.

1
2
3
4
<!-- Added so prototype and JQuery play well together -->
<script type="text/javascript">
  jQuery.noConflict();
</script>

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.



Comments

  1. Akshay February 14th

    Comment Arrow

    Thanks, Very Descriptive.
    Cheers.!


  2. Brian February 18th

    Comment Arrow

    Akshay – Glad it helped you out.


Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

Brian

Brian Abston is a Java Developer in Oklahoma who also loves technology.