When you visit Google.com, the cursor jumps to the searchbox, ready for users to submit a search. Bringing the cursor to the form is called form focus. This is made possible using a simple Javascript. You can set certain elements of the form to focus, when a page is loaded. This is particularly helpful for pages with minimal content, where the intent of the web developer, is to get users to enter data quickly. A login page is a perfect example of such a page. This article will show you how to bring focus on your forms using a simple Javascript.

HTML Form

Let’s create a simple form with two fields called username and password. The goal is to bring the cursor to the “username” field when the page is loaded. First, we assign an “id” and “name” to the form. Let’s call it “login” for lack of a better name. Next, we need to assign an “id” and “tabindex” to each input. We will use “id=’username’” and “tabindex=’1′” for the first input, and “id=’password’” and “tabindex=’2′” to the second input. See the example below.

<pre lang="html">
</input> </input> </input>

Javascript

We can then add a simple Javascript to the end of our form. This code will bring focus, or move the cursor, to a form called “login”, and to a field called “username.” That is it. Simple enough. This is how we bring focus to a form. Check out the demo below to see the result.

<pre lang="html">
<script language="”JavaScript”" type="”text/javascript”">
document.login.username.focus();
</script>

Demo