Home | All Questions | alt.html FAQ > HTML Forms

How do I get the cursor focus on the first text field when the page loads up?

It's a JavaScript issue; there's nothing in HTML for such purposes. A simple way is to use something like

<form ... name="myform">
<input name="myfield" ...>
 ...
</form>
<script type="text/javascript">
 document.myform.myfield.focus();
</script>

from nice-guy-nige

The user can start typing into text fields while the page is still loading. Then when the page has finished loading your script will fire and send focus back to the first field. This would be most annoying! You can test whether a field is in use before firing the focus script. Try this...

<html>
<head>
<script type="text/javascript">

var formInUse = false;

function setFocus()
{
 if(!formInUse) {
  document.theForm.text1.focus();
 }
}

</script>
</head>

<body onload="setFocus()">
<form name="theForm">
<input type="text" name="text1" onfocus="formInUse = true;">
<input type="text" name="text2" onfocus="formInUse = true;">
<input type="text" name="text3" onfocus="formInUse = true;">
</form>
<img src="images/hugePicture.jpg" alt="huge image to slow down
the loading process!">
</body>
</html>

If you start typing in the fields (or even just focus on one), the var formInUse is set to true. The setFocus() function in body onload checks the value of formInUse. If it is false, then the first field gets focus, otherwise nothing happens.

I have put this page online with a 45k(ish) image that slows it down a bit. I tried a bigger version of the image, but it took too long! Anyway, point your favourite browser in this direction... http://www.nigenet.org.uk/bits-n-bobs/fieldFocusTest.html

... and click in the second or last fields before the image finishes loading. When the page is fully loaded, that field will still have focus. Reload the page without clicking in any fields. When the page has loaded, the first field will get focus.

Recommended Resources

Discussion

Related Questions