It seems pretty simple, but still far too many web sites don’t set the focus on the input field that users are most likely to type into when loading a page.

Let’s say you have a page with an HTML form with the ID login with fields named user and password. Here’s the HTML and JavaScript for setting the focus to the user field on page load. IE lets you get away with being a bit sloppy and not properly referencing the HTML form element, but the code below works on Firefox, Safari, and other standards-compliant browsers.

<html>
<head>
<title>Focus Test</title>
  <script>
    function setFocus() {
      var loginForm = document.getElementById("login");
      if (loginForm) {
        loginForm["user"].focus();
      }
    }
  </script>
</head>
<body onload="setFocus();">
  <form id="login" method="post" action="">
    <table>
      <tr>
        <td><div align="left">User Name:</div></td>
        <td><div align="left"><input name="user" type="text"
            size="30" maxlength="30" tabindex="1" /></div></td>
      </tr>
      <tr>
        <td><div align="left">Password:</div></td>
        <td><div align="left"><input name="password" type="password"
            size="30" maxlength="50" tabindex="2" /></div></td>
      </tr>
  </form>
</body>
</html>

You can prove to yourself it works here.

Of course, there are lots of slight variants on this. You could give the field an ID and set the focus directly on it without getting the form first.