Position the cursor on page load

See more about:

The goal

You write a page that asks for the user’s first and last names. What happens when the form first displays? Here are two options:

Cursor not positioned

Cursor positioned

Figure 1. Positioning the keyboard cursor

In the top one, the user has to click in a field before s/he can start typing. In the bottom one, the cursor is already in the first name field. The user can start typing right away.

You can try the first one and the second one.

It’s a small thing. But these details make the difference between a good page and a great one.

The code

How to do it? Add just one line of code to your JavaScript.

<script type="text/javascript">
  $(document).ready(function() {
  First name
  <input id="first_name" type="text">

Figure 2. The code

Line 4 is:


Because it’s in the document’s ready event, it runs when the page first loads. The line tells the browser to “Find the element with an id of first_name.” Remember that # means “look at the id.” Then: “put the input focus on that element.”



How to...