Auto-Focus Form Elements with JavaScript

After digging through the WordPress source code, I stumbled upon this very useful JavaScript method for auto-focusing form elements upon page load. Here is the JavaScript code (place within the document head):

<script type="text/javascript">
	function formfocus() {
	window.onload = formfocus;

…and corresponding (X)HTML markup (abbreviated for clarity):

	<input id="element" />
	<input />
	<input />

In this example, the first form element (identified by id="element") will be automatically focused when the document loads, thus facilitating the process of entering data in the form. This technique would serve users well on login pages (wink, wink;), or anywhere forms are required on a repetitive basis.

Update: [ May 29th, 2007 ] – Here is a similar method of auto-focusing a form element with just a splash of JavaScript. Place the following code into an input element that contains a predefined field value and watch in amazement as the text string is automatically highlighted upon user focus. Here is the JavaScript snippet:


..and here is a “live” example:

..and corresponding code:

<input onfocus=";" value="Select this input element and this text will be highlighted.." type="text">

Update 2012/03/01: The method discussed in this article doesn’t seem to work in newer versions of Chrome. If that sounds like you, try this snippet instead:

<input onclick="" type="text" value="Select this element to highlight text..">

So to see that working in Chrome, try the demo: