OK, this has bugged me for a long time. Many times I’ll come to a site which helpfully auto-focuses on the input element I’m most likely to use (either the username field of a login form, or the query field of a search form). But if the script to make this happen is slow, I’ll often find myself typing over my already half-written search query, or even worse, typing my password (in plain text) into the user name field.
I’ve come up with a few possible solutions. To start, you could just skip the auto-focus code all together and let your users manually select the input they want to type in. This can be fine, but in my opinion, what separates good UI from great UI is when the system seems to know what you want and is one step ahead of you. So how can we avoid the problem while still providing the functionality?
Commenter Joe points out that all three of these techniques fail if you use your browser’s autocomplete to pre-populate the field, but want the web page to focus on the field so you can either hit return or enter a custom username. To handle this scenario I’ve come up with a new recommendation based on focus rather than content:
<script type="text/javascript">
$(document).ready(function() {
var el = $('#query')[0];
if (true !== el.hadFocus) {
el.focus();
}
});
</script>
<input type="text" onfocus="this.hadFocus = true;" id="query" />
So now, instead of checking to see if there’s any content in the “query” field, we’re checking to see if the user has focused on it. If they haven’t, it’s safe to change the focus there. If they have, you know they’re ahead of your code, and you can just get out of the way.
You might want to expand this to check if any field has been focused on. That way if someone starts typing in your search box, you don’t accidentally send them to the username field. But in general, something like the code above should be good in most situations.
Let me know if you see any potential problems.
Continue reading “Auto-Focus Input” »
Recent Comments