Auto-focusing Rails Helpers

Auto-focusing on the first field of a form has thankfully become standard practice. A quick bit of javascript and it’s done.

Here are some ways to handle auto-focus:

body tag onload

Pros

Simple

Cons

Not as simple to integrate into a Rails app if you share layouts across multiple controllers/views.

Example

Gmail login page

<body onload="document.login.userName.focus();">

Custom javacript hook

Pros

Standard, application wide control

Cons

Complicated, harder to debug in varying browsers

Example

// Auto-focus first element
Event.observe(window, 'load', function() {
  var e = $A(document.getElementsByTagName('*')).find(function(e) {
  return (e.tagName.toUpperCase() == 'INPUT' && (e.type == 'text' || e.type == 'password'))
          || e.tagName.toUpperCase() == 'TEXTAREA' || e.tagName.toUpperCase() == 'SELECT';});
  if (e) e.focus();
});

javascript snippet after field

Pros

Still simple, more control

Cons

Embedded script not as clean

Example

37Signals Highrise group page

<input id="group_name" name="group[name]" size="30" type="text" />
<script type="text/javascript">
  //<![CDATA[
  $('group_name').focus()
  //]]>
</script>

Auto-focusing with Rails helpers

For an application I am working on I found the best approach to be the last technique. The code snippet above (from Highrise) could be generated by the following Rails helpers:

<%= text_field :group, :name %>
<%= javascript_tag "$('group_name').focus()" %>

As I used this pattern throughout my app I started to wish I could say this:

<%= text_field :group, :name, :focus => true %>

On of the best things about Ruby is you can mock up the desired syntax, and then create the code to fulfill it. The code I came up with is now the focus_fu plugin.

Installation

./script/plugin install http://svn.depixelate.com/plugins/focus_fu

Supported helpers

text_field
password_field
file_field
text_area
check_box
radio_button
text_field_tag
password_field_tag
file_field_tag
text_area_tag
check_box_tag
radio_button_tag
select
select_tag

Usage

Add :focus => true to the end of a supported Rails helper.

Examples

<%= text_field :user, :name, :focus => true %>
<%= text_field_tag :user_name, nil, :focus => true %>
<%= select :post, :category, %w(rails python), :focus => true %>
Comment or question via
FYI: This post was migrated over from another blogging engine. If you encounter any issues please let me know on . Thanks.