Prototype, and JQuery inside Rails Application

It has become common practice to use JQuery as the javascript library of choice for Ruby on Rails  applications with the latest versions of rails using JQuery.  But If you have an Rails application that is already using Prototype, it may create problems to replace that with JQuery . And sometimes, you just simply need both to work at the same time.

Use Prototype/Scriptaculous with JQuery

 First, in our application layout, we’re going to get rid of <%=javascript_include_tag :defaults %> and include each javascript file explicitly just to make things a little easy to understand and a little more straight forward.

 So we have replaced defaults with 

<%= javascript_include_tag 'prototype', 'scriptaculous', 'application' %>

Now, we’ll add in JQuery, by downloading the latest version of JQuery from the JQuery Download page from the JQuery Website

<%= javascript_include_tag 'prototype', 'scriptaculous', 'jquery', 'jquery-ui', 'application' %>

Right under that line, in your Rails application layout, we’ll insert the one-liner that makes JQuery play nicely with Prototype, YUI, etc.

This will come under script tag

var $j = jQuery.noConflict();

This allows jquery to be called along with scriptaculous without any conflicts,the only difference is all jquery functions should be called with $j instead of $

e.g. $j('#div_id').stuff instead of $('#div_id').stuff

If you simply want the ability to use both libraries together in your application


Notice the first line uses the Prototype element id selector, $ with a Scriptaculous effect, and the second line uses the new noConflict JQuery selector $j.


Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers