I am available for freelance work! Click here to email me.

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

Recommend Me

If you found this post or anything else on this site of any use, then please take the time to recommend me on Working with Rails.

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

  • Diosan
    This looks great... but I have a problem, I am rails newbie so It is probably because i am not doing something correctly.... the problem i have is that I dont have the file application.html.erb
  • Great article!

    I'm truly a newbie when it comes to RoR and this kind of posts are really helpful for me.

    Just one thing, in the very first example of jQuery, you are using the attribute target with the value "blank", when it should be the reserved name "_blank", so it opens a new window for each link, instead of using the window named "blank" for all the links.

    Cheers :)
  • Amazing! but did not understand:
    >> I will say one thing though: a lot of the time you may just find it easier to use page << at certain times:
    On rails 2 weeks.
    Sorry for bad English
  • Helton Marinho
    good job!
    I prefer jQuery why is very simple, small code and good documentation.

    In my jobs dont exists time to developed in complex code, but i need good interface, functionally and compatibility. I has in jQuery.

    is not apology, ok?

    // find marinho in table...
    $('table tbody tr td:contains(marinho)').css({
    color: 'red',
    backgroundColor:'#CCC'
    });
  • Ken
    Man, I sure hope this works. I'm a frontend developer (read CSS tech head), and about 90% into the project, my client said "oh yeah, hey, rails has these helpers... scriptaculous will explode because of your jquery" lolol.

    Of course, she's only using helpers, so if jRails works, it'll be a godsend. I find out tomorrow. Cross your fingers!
  • Sam
    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.
  • Sorry again, my fault : it's "addClassName" and not "addClass" in Prototype ;) (copy-paste just fooled me)
  • Hay
    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/
  • 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.
  • @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.
  • 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
  • Tony
    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!
  • @Marko - Thanks for that. Updated.

    @Harry Bailey - They seem to show up for me. What browser/os are you using?
  • Harry Bailey
    The class="ruby" code blocks are not showing.
  • Marko
    You can also shorten the jQuery examples :)

    $(function() {
    $('a[rel=external]ë).attr(ítargetí, ëblankí);
    });

    and

    $('#the-link').click( function() {
    $('#the-div').addClass('hello');
    });
  • leethal
    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 ; )
  • Hi Remy,

    Thanks for that. I've updated the examples.
  • 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');
    });
  • Thanks for this!

    Very nice looking site, by the way.
blog comments powered by Disqus
Purify - Issue Tracker

Jim Neath is a 26 year old Freelance Ruby on Rails developer from Manchester, UK.

Recommend Me

Categories