Setting Default Focus Using MonoRail/Prototype Ajax Libraryw


It’s the little things that make web applications a bit more user friendly.  One of these very basic things is simply making sure that some element, ideally the most important one (i.e. search box, first data entry element, etc.), is set to have default focus when the page loads.  Think about those precious seconds that would be lost if, when you browsed to Google.com, you had to set focus to the search box yourself.  Ugh!  🙂  (Some if this may be the keyboard-addict coming out in me…)

What makes this even worse, is that it’s really not that hard to do this in your pages.  Here’s just one example of how I’m doing it on my current MonoRail project using the fabulous Prototype javascript library.

I’ve built a simple reusable “sub view” named defaultFocus.brail which can be called from any of my pages, passing in the id of the html element I want to have default focus.

views/common/defaultFocus.brail

<script type="text/javascript">

   1:     Event.observe(window, 'load', function() { document.getElementById('<?brail output controlIdToFocus ?>').focus(); });

</script> </div>

So then, an example of this can be used in one of your views…

views/home/index.brail

   1: <?brail OutputSubView('/common/defaultFocus', { 'controlIdToFocus':'searchCriteria' }) ?>
   2: <input type="text" name="searchCriteria" id="searchCriteria" />

Pretty simply stuff.  Yet you’d be surprised how many web applications and pages out there don’t do this!  One example I just noticed today is in the Community Server blog dashboard in the “Tag Editor” dialog box. 

cs_tageditor

This niftly little web dialog window has a jazzy slide down effect when it opens, but lacks a very basic thing such as setting the default focus to the “Name” input box.  On a related note, if I’m adding a new tag, wouldn’t I want it to be enabled by default most of the time?  Again, just a little thing…

I’m certainly guilty of these things myself sometimes, but I just wanted to encourage folks (including myself) to be good web usability citizens and look for opportunities to make little enhancements like this that can make web applications that much easier to use.

As usual, I’ve updated my ongoing sample code library to include these changes.

Unit Testing NHibernate DALs – What Are You *Really* Testing?