Smart way of focussing a text input on page load for heavy pages

27 / Aug / 2012 by raj 0 comments

Let’s say you have a login page which contains a form with username and password field in it (offcourse, along with a submit button).
Let’s say being much focussed towards user convenience with the user interface, you want to put the cursor in the username field of your form as soon as the page loads. You just go ahead and write-
[javascript]
$(document).ready(function{
$("#username").focus();
});
[/javascript]

And you think, voila, its done. That was pretty easy.
This code is good enough for small to average sized pages. However, if the html page is huge or if the user is on a slow connection, you have just planted a source of big frustation for him.

You might have fallen into a scenario, where you need to enter username and password to log in. You just go ahead and type your username, press tab to switch to password field and start typing and in the halfway, the cursor went back to the username field and you end up typing remaining half of your password in the username field. Annoying isn’t it? This keeps on happening with me when i try to log in to my gmail account, and I hate google for this(I hope they are not reading my blog). But to your surprise, the jquery code written at the beginning of the blog is the real culprit!

What’s happening here is, the user see and start typing into the username field before the entire page is loaded(remember, the page may contain heavy images and text fields are loaded and become visible to user much before than the images). When the entire page is loaded, $(“#username”).focus(); is fired and the cursor is put into the username field.

There are two ways to deal with this situation.

1. Don’t wait till the entire page loads. Use inline javascript to put the cusor in username field as soon as the field is loaded.
[javascript]
<input name="username" id="username" type="text"/>
<script type=text/javascript>
$("#username").focus()
</script>
[/javascript]

2. If you want to stick with $(document).ready(), you can take the following approach.
[javascript]
$(document).ready(function(){
var $username=$("#username");
if($username.val()==”){
$username.focus()
}
});
[/javascript]

Hope it helps and saves your users from a lot frustation.

Raj Gupta
raj.gupta@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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