Thursday, April 17, 2008

Highlighting Active Rows in Forms

April 17th, 2008 By: Daniel

What can be done to make the ubiquitous form element a little more usable and appealing? That was a question we asked ourselves on a recent project and one of our answers was to highlight the active row. It’s easy to change the appearance of the active input element with the focus pseudo-class in css, but a quick Google search didn’t reveal an easy way to highlight the containing tr element and so I ended up rolling my own implementation.
First I added the following javascript to public/javascripts/application.js:
/* For highlighting active rows */
function highlight_row_on_focus(e) {
  $(e).up("tr").addClassName("focused_row");
}
function unhighlight_row_on_blur(e) {
  $(e).up("tr").removeClassName("focused_row");
}
And then I styled my rows in public/stylesheets/application.css:
.evenrow {
  background-color: #f1f5fa;
}
tr.focused_row {
  background-color: #d7e0ea;
}
To make the view a little cleaner I added a quick helper to helpers/application_helper.rb:
def element_options_with_highlight(opts = {})
  {:onfocus => "highlight_row_on_focus(this.parentNode)", :onblur => "unhighlight_row_on_blur(this.parentNode)"}.merge(opts)
end
So now in your views all you have to do is add an element_options_with_highlight to the input elements in your forms:
<table>
  <tbody>
    <tr class="<%= cycle('oddrow', 'evenrow') %> required">
      <td><label for="username">Username:</label></td>
      <td><%= text_field_tag :username, @username, element_options %></td>
    </tr>
  </tbody>
</table>
Then check your layouts to make sure the Scriptaculous libraries are being loaded and your javascript and stylesheet is being sourced and voilá! you now have a form that highlights the active row as you tab through.

No comments:

Post a Comment