Fixing the auto-focus

Focusing on an input element just as the user loads the form will easily be a great usability enhancement.
However, doing it the wrong will cause problem for at least some users.

Setting focus in onload() event

Most websites make the mistake of setting the focus in the onload() event. This can cause troubles for the user.

<body onload='document.myform.username.focus();' >

Imagine a login form. The web page is being loaded and the login form appears.
The user starts typing in his username or email. With the browser’s auto-complete on, the user does not have to
type the entire name. Just press the first few letters and the browser will display the username from its history.

By the time the web page completely loads up, the user would have entered the user name and would have started with the password.

Now that the web page with all the images loaded completely, it triggers the onload() event. It sets the focus in the username field.

Meanwhile, the user was already busy typing the password. Part of the password gets typed in to the user name field.

If the user failed to notice that the user name has part username and part password, he will get a login error which will be confusing because the user thinks he entered the login correct. Now the user has to enter the user name and password again.

Correcting the auto-focus

One way to avoid the troubles with the wrong auto-focus is to avoid auto focus if the user has already started typing.

<body onload='if(!document.myform.username.my_no_focus){document.myform.username.focus();}' >
...
...
<input type="text" name="username" onkeydown="this.my_no_focus = true;">

Another rather ‘hack’ version of a better auto focus is to do the focus call just after the field’s HTML code.

<input type="text" name="username">
<script>
document.myform.username.focus();
</script>

The HTML5 autofocus solution

In HTML5, you can set an autofocus attribute in the input field like this:

<form name='myform' id='myform'>
<input type='text' name='username' autofocus>

Since the browser sets the auto focus as the page loads, the focus shift problem does not occur.

Comments on this entry are closed.