How to have jQuery and prototype.js in the same project
I’m a big fan of jQuery. This librarie is just the best and simplest one around. I really noticed it when I wanted to get rid of jQuery in TimmyOnTime and try to use prototype.js instead, just to be more “rails-oriented” (that’s a pretty lame excuse don’t you think?)
Why I didn’t like prototype.js
There was not a lot of javascript written for the project so I thought that getting rid of jQuery and using prototype.js would be easy. It turned out to be hell on earth. Prototype.js made me feel like I was back in the 90s writing C++. A simple click event turns out to be a awful lot of ugly code with ugly function names.
Example, if I wanted to show the content of a DIV I clicked in prototype.js, I would use things like Event.observe, bindAsEventListener, a mix of native DOM element and prototype.js element, and worst of all, an unintelligible documentation.
jQuery as a complete different way of doing it in a single easy-to-understand line :
$(“#a_div”).click(function() { alert($(this).text()); });.
As simple as that!
The problem
I wanted to use some interface element in Rails that requires prototype.js so I had to have both librairies. The problem is that there’s a conflict between them. Prototype.js doesn’t seem to give a damn about it but jQuery is nicer with you. It offers a noConflict method.
With Rails, prototype.js is the default librairie so to override this, you could do
-
<%= javascript_include_tag "prototype", "jquery" %>
-
<script>$j = jQuery.noConflict();</script>
This way, you will have to use $j instead of $ to call jQuery.$ would still call prototype.
Another thing you could do is to use jQuery on Rails and don’t give a damn about scriptaculous. I personally prefer to use librairies that are fully tested instead of using a “by-pass” that could break my code. It’s your choice…