Imagine your web site — made elegant, but simple and standards compliant, yet usable and for less time & money than you might think.

Input focus onload

Some web sites, such as big search engines, (Google, or Yahoo! for example) and other types of commercial sites often will feature a very prominent main search field. Possibly a search field on every page.

When this is the case, its a very good practice to make SURE the user always has their mouse cursor inside (or in focus) the main input field right from the get-go. No one wants to have to click inside a field every time they visit when its the main point of the site in the first place.

Here's an easy way to achieve this.


The problem with using the above code is that you'd have to put it into each and every single input element, for every page that you wish for it to have attain focus by default. And you probably already know where I'm going with this... it's unacceptable.

What we will need is to create a function that will crawl the DOM looking for the first input element with a type attribute of "text" that also has no default value, and then apply focus only to it.

Here's one such example.

function focusInitialField() {
  var fields = document.getElementsByTagName('input');
  
  for ( var x = 0; x < fields.length; x++ ) {
    if (fields[x].getAttribute('type') == "text" & fields[x].value == "") {
    try{fields[x].focus();}
    catch(ex) {}
    break;
    }
  }
}

focusInitialField();

I chose to call this function focusInitialField() but you are welcome to call it whatever you like. If you can think of a shorter, faster, or all around better solution, then by all means please share.

Personally, I have found it beneficial to call to it right before the closing body tag, so that it can fire right after the document finishes fully loading.

Jun 21, 2009