Using jQuery with Ruby on Rails

June 18th, 2008

By default, Rails comes packed with the Prototype javascript library and the effects library, Scriptaculous. While this is all well and good sometimes you want a change. I personally prefer jQuery to prototype. I don’t have any beef with prototype, infact I used it for about a year before even getting into rails, but I just prefer the jQuery syntax and selectors.

jQuery

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

jQuery, like Protoype, is a javascript library that takes care of much of the grunt work you face day to day. It helps to resolve your cross browser issues, makes creating dom elements easier and various other things.

Some Prototype / jQuery Examples

I’ll post a couple of code examples so you can see the difference in the libraries. I’m not saying these examples are the best way to do things (I know people will say otherwise), they’re just here to help you understand the libraries.

Note: I haven’t tested these examples, although I believe they should all work.

Open all links marked with rel=”external” in new windows

Prototype

document.observe('dom:loaded', function() {
  $$('a[rel~=external]').invoke('writeAttribute', 'target', 'blank');
});

jQuery

$(function() {
  $('a[rel=external]').attr('target', 'blank');
});
Changes class of a div on click of an element

Prototype

$('the-link').observe('click', function() {
  $('the-div').addClass('hello');
});

jQuery

$('#the-link').click( function() {
  $('#the-div').addClass('hello');
});

For more information on jQuery syntax and all the bells and whistles, have a look at the jQuery Documentation.

More Prototype <=> jQuery Examples

Remy Sharp has also published a walk through comparison between Prototype and jQuery to help developers go from one language to another.

Hello, jRails!

Want to use jQuery but love your prototype helpers too much? Fear not! Enter jRails, stage left.

jRails is a drop-in jQuery replacement for Prototype/script.aculo.us on Rails. Using jRails, you can get all of the same default Rails helpers for javascript functionality using the lighter jQuery library.

That basically says it all.

Installing jRails
ruby script/plugin install http://ennerchi.googlecode.com/svn/trunk/plugins/jrails

Bosh. All sorted. The plugin will install all the required javascript files over to public/javascripts. Unless you’re planning on using prototype along side jQuery you will probably want to delete the prototype files in your javascripts folder.

Including jQuery and Friends

Now you want to open up your application.html.erb file and edit the javascript include tag:

<%= javascript_include_tag :defaults %>

This will now include all the jRails files instead of the prototype/script.aculo.us files. You might want to just include the files that you need instead of all these:

<%= javascript_include_tag 'jquery' %>
<%= javascript_include_tag 'jquery-ui' %>
<%= javascript_include_tag 'jrails' %>

Using jQuery in RJS

You don’t have to do anything. Brilliant. That’s the main point of the jRails plugin. It does all the grunt work for you. Just use your helpers as you normally would.

I will say one thing though: a lot of the time you may just find it easier to use page << at certain times:

page << "$('span#bacon').text('CHunKy');"

jQuery UI

jQuery UI provides abstractions for low-level interaction and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.

The core of the library revolves around different mouse interactions, namely drag and dropping, sorting, selecting, and resizing, as well as a powerful set of effects.

On top of the core interactions are built a number of reusable widgets, including accordions, date pickers, dialogs, sliders and tabs.

I was going to write some blurb about jQuery UI but I feel that this quote says it all, really. Want to know more? Check out the jQuery UI site

Some jQuery Scripts

I thought I’d list a couple of helpful scripts to help you on your way to the wonderful world of jQuery. So here goes:

Validation

Validation is a great form validation script by Jörn Zaefferer. Unobtrusive, sexy and just plain brilliant.

Lightbox

jQuery lightBox plugin is simple, elegant, unobtrusive, no need extra markup and is used to overlay images on the current page through the power and flexibility of jQuery´s selector.

lightBox is a plugin for jQuery. It was inspired in Lightbox JS by Lokesh Dhakar.

The better way to know what is jQuery lightBox plugin, click the Example tab above and see it in action.

Everybody loves a lightbox, surely? The jQuery Lightbox script is based on by Leandro Vieira Pinho.

If you have any other suggestions for great jQuery scripts, let me know and I’ll add them to the list.

(Possibly) Related Posts

You can follow any responses to this entry through the RSS 2.0 feed. Trackback from your own site.

22 Responses to “Using jQuery with Ruby on Rails”

  1. June 18th, 2008 at 3:08 pm - Jeremy Says:

    Thanks for this!

    Very nice looking site, by the way.


  2. June 18th, 2008 at 4:17 pm - Rémy Says:

    Nice article, but I think you can shorten a bit the Prototype examples :

    document.observe(”dom:loaded”, function() {
    $$(’a[rel~=external]‘).invoke(’writeAttribute’, ‘target’, ‘blank’);
    });

    and

    $(’the-link’).observe(’click’, function() {
    $(’the-div’).addClass(’hello’);
    });


  3. June 18th, 2008 at 5:01 pm - Jim Neath Says:

    Hi Remy,

    Thanks for that. I’ve updated the examples.


  4. June 18th, 2008 at 8:37 pm - leethal Says:

    Some more code samples for the jQuery-curious here: http://github.com/leethal/sample-rails-apps/tree/master/jquery_and_ajax. Shows how to use will_paginate with jQuery ajax, and how to submit a form with ajax, too. All unobtrusive and awesome ; )


  5. June 19th, 2008 at 12:13 am - Marko Says:

    You can also shorten the jQuery examples :)

    $(function() {
    $(’a[rel=external]‘).attr(’target’, ‘blank’);
    });

    and

    $(’#the-link’).click( function() {
    $(’#the-div’).addClass(’hello’);
    });


  6. June 19th, 2008 at 1:23 am - Harry Bailey Says:

    The class=”ruby” code blocks are not showing.


  7. June 19th, 2008 at 9:19 am - Jim Neath Says:

    @Marko - Thanks for that. Updated.

    @Harry Bailey - They seem to show up for me. What browser/os are you using?


  8. June 19th, 2008 at 10:51 am - Tony Says:

    Yeah the class=’ruby’ blocks don’t show for me either. I’m using Leopard and Safari. Just tested it on Firefox and it works there.

    Otherwise great article, will definitely have a play around with jQuery!


  9. June 19th, 2008 at 11:39 am - Remy Sharp Says:

    Hi there, I’m not a Ruby developer, but I did write some slides on going from Prototype to jQuery and visa versa (i.e. showing how xyz is done in each library) - I thought it might be of interest if you Rails chaps are used to Prototype:

    http://www.slideshare.net/remy.sharp/prototype-jquery-going-from-one-to-the-other


  10. June 19th, 2008 at 2:09 pm - Jim Neath Says:

    @Remy Sharp: I actually read your slides when they were posted on Ajaxian. I’ve added them to the article :) Thanks for reminding me.

    Also I’ll try and figure out the problem with the ruby blocks not showing up.


  11. June 19th, 2008 at 2:14 pm - Nome do Jogo » Artigo » Rails Podcast Brasil - Epis Says:

    [...] Using jQuery with Ruby on Rails [...]


  12. June 19th, 2008 at 2:25 pm - Jim Neath Says:

    I have fixed the code not showing up in Safari. It appears that I forgot to replace the < and > with < and &td; respectfully. Like a fool.


  13. June 20th, 2008 at 9:23 am - Using jQuery with Ruby on Rails Says:

    [...] Jim Neath has put together a handy guide on Using jQuery with Ruby on Rails. [...]


  14. June 20th, 2008 at 2:30 pm - Hay Says:

    Although the Lightbox plugin looks very nice and works beautiful it has one very big drawback: it is licensed under a Creative Commons Attribution-No Derivatives license, meaning that you can’t alter the code to fit it to your own needs. This is not the case with the original prototype-based Lightbox, which is licensed under a Creative Commons Attribution license. A free (BSD-licensed) alternative for jQuery can be found here: http://code.google.com/p/jquery-lightbox/


  15. June 20th, 2008 at 4:34 pm - jQuery + RoR — Tablosign Says:

    [...] Tutorial básico para utilizar jQuery en on Rails. En inglés pero muy fácil de entender. 0 # [...]


  16. June 25th, 2008 at 6:49 pm - jQuery: JavaScript library « IT Passion Says:

    [...] Using jQuery with Ruby on Rails [...]


  17. June 26th, 2008 at 1:41 pm - Rémy Says:

    Sorry again, my fault : it’s “addClassName” and not “addClass” in Prototype ;) (copy-paste just fooled me)


  18. June 26th, 2008 at 3:30 pm - links for 2008-06-26 « Amy G. Dala Says:

    [...] Using jQuery with Ruby on Rails | Ruby on Rails (tags: ajax tutorials javascript rails ruby reference web_dev) [...]


  19. June 27th, 2008 at 12:48 am - Space Babies » Blog Archive » jQuery here I come Says:

    [...] and more lightweight, what more could a boy want? Well, my built-in view helpers darn it! Enter jRails (stage left, as they say). All jQuery goodness, no Prototype badness, I [...]


  20. July 1st, 2008 at 3:36 am - links for 2008-07-01 at brant interactive Says:

    [...] Using jQuery with Ruby on Rails | Ruby on Rails (tags: jquery rails javascript) [...]


  21. July 10th, 2008 at 1:13 am - Paper Bits – links for 2008-06-26 Says:

    [...] Using jQuery with Ruby on Rails | Ruby on Rails (tags: howto ruby ajax rails webdev) [...]


  22. July 11th, 2008 at 11:19 pm - Sam Says:

    Nice article. jQuery seems a lot nicer in these examples, but it can get pretty messy pretty quickly. I recently wrote a in-browser code editor with prototype, and I think it would’ve been scruffy with jQuery.


Leave a Reply

Jim Neath is a 23 year old Ruby on Rails developer from Manchester, UK. Contact Jim Neath

Recommend Me

Categories

Stalk Me