Page load form field focusing: The nice way
Let’s say there’s your form on your web page. That’s not too far of an assumption is it? It could be a sign-in form, a search form, or just a simple input box, but the point is it’s important. In fact, it’s so important that the first thing your users are going to do when they access your page is to use that form. You know this and as a nice gesture you make the initial field focused on when the page loads. This is a great usability feature and this post is about how to do it and be nice to your users.
Here’s a generic version of the Javascript most sites use. You’re code may differ if you are using IDs or a Javascript library.
document.forms[0].elements[0].focus();
Just pop that in an body onload statement and we’re done, right? Well, while the page loads and the initial field has focus, we’re not really taking into account network lag and how web pages are rendered.
See, that onload statement won’t run until the page is finished loading and sometimes that can take a bit. As users become familiar with your website they take action the second they can, not when the page is finished. Thus, the user could be entering search terms only to have the javascript trigger, re-focus on the field, and they type over what’s there. Frustrating. Even worse, if that field was a part of a sign-in form, their username could already be entered and they’re working on the password when the javascript triggers. If they aren’t paying attention they just entered their password in the username box. Very frustrating.
So what do we, as web developers do about this? It’s a really simple fix; We check to make sure there is no value in the field before focusing on it. Here’s our code from above, but now a little smarter:
var field = document.forms[0].elements[0];
if (field.value === '') {
field.focus();
}
See, I told you it was easy. If you don’t have something like this on your site what are you waiting for? Now, if only my bank would read this and fix their site!
