Christian Heilmann

Tackling automatic field focus usability issues

Monday, October 9th, 2006 at 4:53 pm

One of my greater annoyances on the web is sites that automatically focus a form field when the page has loaded. Supposedly this should make it easier for you to use the product, as you are to log-in anyways, but there is one real problem with this.

If you try the demo page for a normal autofocus and start typing in your details, it can happen that you are already in the middle of your password when the page is ready and the focus gets shifted to the email field. I have seen this happening in Internet Cafes, where people inadvertedly revealed their passwords that way.

The reason is the simplicity of the scripts applied to focus the field when the page has loaded, which sometimes is as rudimentary as:

window.onload = function() {
document.getElementById( ‘email’ ).focus();

Now, I wondered how to make that better. A simple solution would be not to use onload on the window (and thus waiting for the document and all dependencies to be loaded before you proceed) but use onAvailable or equivalent solutions on the element itself instead. However, if the element to highlight is not the first, that would still make it possible to enter other data until the focus gets taken away from you.

Next I considered to read out the event target when the page has loaded and assume that if the target has a node name, someone is entering data. That proved to be to flaky (as [link:,Chris Kaminski,colleague met] predicted, darn you!) as MSIE told me undefined whenever.

Thus, I dug deeper into my memory of form elements and unveiled the idea of value versus defaultValue. The latter, rather less known is the value set in the HTML attribute, whereas the value is the value of the field. Value changes when the user enters data or changes the element’s state (in case of checkboxes), but defaultValue doesn’t.

Using this information it is easy to set up a better autofocus script that will not focus the element when any of the data in the form deviates from the original settings in the HTML.

var isfocused = false;
var elms = [‘email’,’pw’];
for(var i=0;i var elm = document.getElementById(elms[i]);
if(elm !== undefined){
if(elm.value != elm.defaultValue){
isfocused = true;


if(isfocused != true){


All you need to edit is the elms array listing the IDs of all elements to check :-).

Share on Mastodon (needs instance)

Share on Twitter

My other work: