Thursday, August 10th, 2006

Unobtrusive Javascript and Ajax for Rails

Category: Accessibility, JavaScript, Ruby, Unobtrusive JS

Luke Redpath and Dan Web have released Unobtrusive Javascript for Rails. If you’ve spent time with the Rails javascript helpers, you know that they can be a huge time saver, but tend to produce some nasty code like this:

javascript

  1. <form onsubmit="new Ajax.Request('/subscribe/add_ticker', {asynchronous:true, evalScripts:true, onLoading:function(request){ticker_loading()}, parameters:Form.serialize(this)}); return false;" method="post" action="/subscribe/add_ticker">
  2. ....
  3. </form>

So you have all of your behavior mixed in with your content, with inline javascript everywhere. Thats bad for business! Dan has written more extensively on how “Rails is the devil on your (client-side) shoulder”.

The Unobtrusive Javascript plugin changes that. It allows you to write:

  1. < % apply_behaviour "#mylink:click" do |page, element|
  2.     page.alert "You clicked me! Now watch me fade..."
  3.     element.visual_effect :fade
  4.   end %>

To attach fades to links in a page. Or use it with the builtin rails tag helpers:

  1. < %= content_tag "div", "My funky box", :onclick => "alert('Hello World!')" %>

The resulting code is attached on load, using prototype events and all that stuff. Very nice! The plugin uses event:Selectors for attaching events dynamically and placing them into an external javascript file. Luke has written a recent note about a fix needed if you are using edge Rails, and also recommends use svn:externals to keep the plugin up to date. The project home page is here, as of right now it just contains the rdocs. I may just have to check this out for my rails work…

Posted by Rob Sanheim at 9:39 am
5 Comments

+++--
3.5 rating from 40 votes

5 Comments »

Comments feed TrackBack URI

Thanks for the heads up Rob.

Just one small note, the latest version of unobtrusive js is using Dan’s own lowpro js library which includes improved event handling code as well as a modified version of event:Selectors – I don’t know the ins and outs of Dan’s JS wizardry but the code is there for everybody to see. Feel free to grab lowpro.js for use elsewhere as well, I know Dan is planning on releasing this separately soon.

Comment by Luke Redpath — August 10, 2006

Oh, and I should mention the plugin has its own website, currently just the rdocs:

http://opensource.agileevolved.com/unobtrusivejs/

Comment by Luke Redpath — August 10, 2006

Thanks Luke, I updated the post to have that link, too.

Comment by Rob Sanheim — August 10, 2006

Grab 0.2.3 whilst its hot:

http://www.lukeredpath.co.uk/index.php/2006/08/10/unobtrusive-js-022-the-two-in-one-day-release/

Comment by Luke Redpath — August 10, 2006

Interesting, Ajax for Python -> Dango?

Comment by Nbus — August 11, 2006

Leave a comment

You must be logged in to post a comment.