JavaScript: how to set focus in page load

Apr 01 2009

You have this nice little login form in your home page…login-form

…and you want people to directly login as soon as they get to the site. 

To facilitate this, you have set up a small JavaScript code to set the focus automatically to the username text box:

function onPageLoad() {

There is a caveat here though.

Usually programmers place their JavaScript code in the HTML such a way that the code is run only after all the elements in the page is loaded.

Now the user comes to your site, the login form loads, but some other elements in the page are still loading.

The user starts typing in the username, then moves on to fill the password:


Your page completes loading now, and the JavaScript executes and sets the focus to username textbox. The user does not know this, he is still typing the password.



The same usability glitch can occur in many similar situations involving user action.

In this specific situation, you can modify the code to something like:

function onPageLoad(){
      if(document.form.username.value.length==0) {

You can also try executing the script as soon as the form completes displaying, but as far as I know there are no reliable ways to do these because different browsers implement stuff differently. Even in the same browser things work inconsistently in different scenarios.

14 responses so far

Leave a Reply