Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

Buttons? What buttons?

Posted on July 31, 2008 18:52 Tagged with button_to, javascript, rails, unobtrusive.

So we’re all nice little RESTful developers and everything is working great. There’s just one little annoyance. To be able to let our users create, modify or delete resources we have to use a form. But then we have all these buttons messing up our rounded corners, because form elements aren’t treated as every other element in the DOM by the browsers and are difficult to style. Rails has a hack wherein it can make a link appear as though it works with POST requests. It does this by adding a hidden form which is submitted when the link is clicked. This works fine, but it’s obtrusive and – dare I say – not very DRY. If we turn this on its head, we can make it both unobtrusive and DRY.

To do this, we start out with the form instead of the link. This will make it unobtrusive, because a user with no JavaScript will just get a button instead. The JavaScript will hide the form and add a link which submits it when clicked. To make it DRY, we just extract this JavaScript into an external file:

document.observe('dom:loaded', function(){
  $$('form.button-to').each(function(form){
    var link = new Element('a', {href:'#', 'class':'button-to'});
    link.update(form.down('input[type=submit]').value);
    link.observe('click', function(e){
      e.stop();
      form.submit();
    });
    form.insert({after:link});
    form.hide();
  });
});

We don’t even have to worry about the server side which spews out the HTML, because this works with the existing button_to helper. All forms with the class “button-to” will be replaced by links.

Now our apps can be unobtrusive, DRY and pretty.

The Sasquatch: Fact Or Fiction?