Selecting the First Field of a Form in Prototype

November 21st, 2007 No Comments »

Hey, I know it has been a while, but I thought I’d post a useful snippet I wrote for use in rails.

When you load a page with a form, you have to stop to think about adding in an onload event that will select the first field. Should I do it inline because then as soon as the form is loaded I have the first field selected and any images that are slow-loaded won’t ruin my user experience? Do I just do it onload and trust that my users have fast enough connections? OR DO I DO THIS!?!?!?

document.observe('dom:loaded', function() {
  if (form=$$('form.set-focus')[0]) {
    form.focusFirstElement()
  }
});

Just load that in your application.js, and you’re great!

“But oh no!” they will say, “if I have any images then this will ruin the user experience when load-times are long!” Lets lay this to rest with a quote from the prototype api:

One really useful event generated by Prototype that you might want to observe on the document is “dom:loaded”. On supporting browsers it fires on DOMContentLoaded and on unsupporting browsers it simulates it using smart workarounds. If you used window.onload before you might want to switch to dom:loaded because it will fire immediately after the HTML document is fully loaded, but before images on the page are fully loaded. The load event on window only fires after all page images are loaded, making it unsuitable for some initialization purposes like hiding page elements (so they can be shown later).

Edit: Now searches for the first form on the page with a ’set-focus’ class, and sets focus to the first field. This is to prevent the page from scrolling if the first form on the page is past bottom of the window. The first implementation was pretty naive, but this is pretty solid.

Autoloading ActiveRecord Associations in the Console

August 24th, 2007 1 Comment »

So, want to automagically load associations in script/console? I know I do. This little snippet did the trick, I got it here so have fun and don’t break anything!


# override the console's current behavior of not loading things automatically
class ActiveRecord::Associations::AssociationProxy
  def inspect
    load_target unless loaded?
    @target.inspect
  end
end