Categories
Web Development

Make Login Pages Autofocus

I see this way too often and it gets on my nerves. If you have a page that’s main purpose is a form, such as a login page, please make the page autofocus to the first field in the form. Having to tab or click on the first field is a nuisance. Even big sites make this mistake.

If you don’t care about IE you can do it as simply as:

<form method="post" action="/">
<p>
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" autofocus="autofocus"/>
</p>
<p>
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" />
</p>
<p><input type="submit" name="login" value="Login"/></p>
</form>

Since autofocus is boolean you technically don’t even need to specify an attribute value.

To do it with IE in mind you could use the following JavaScript below the form (no library needed):

function focusForm(){
    setTimeout(function(){
        try {
            // id of element to focus on
            var elem = document.getElementById(‘username’);
            elem.focus();
            elem.select();
        } catch(e){}
    }, 50); // setTimeout to fix IE bug
}
focusForm();

Note the use of select() so if the form reloads due to an incorrect password the field is not just in focus but the contents highlighted. There is also a setTimeout() since IE, at least some older versions have trouble with this if it happens too quickly. 50 should be fast enough that it won’t be noticed by humans.

See how simple that is? No excuses for not fixing this 😉 .

Leave a Reply

Your email address will not be published. Required fields are marked *