html tutorials web design help css tutorials free web graphics diy search engine optimization

Form Trick: Pre-load the Cursor in a Text Box

Have you ever noticed when you go to the Google search engine that the cursor is already loaded into the search field? If you haven't clicked anywhere on this page when it loaded, you should see the cursor is already inside the Name text input field below, ready for typing.
What's Your Name:
What's Your Game:

How That Was Done

To have the cursor in a specific form field when the page loads, a JavaScript command is placed in the body tag:
<body onLoad="self.focus();document.boogie.jack.focus()">

That tells the browser an event should happen when the page loads. The event, in this case, is focus. Since it's a text box we're later specifying the focus to be . . . um, focused on, the focus takes the form of the cursor being placed in the text box.

Where the JavaScript says "boogie" is where you'd type the name of your form, and you'd add that name to your form like this:

<form name="boogie">
Where the JavaScript says "jack" is where you'd type the name of the form element you want the cursor to be placed in, then add that name to your text input code.
<input type="text" name="jack">
That tells the browser which element of the form the event should be placed in. You can name "boogie" and "jack" anything you like, just so the names you use in the body tag and form tag are the same and don't contain any special characters or words reserved for JavaScript.

The Disadvantages

  • When someone wants to use their Backspace Key on their keyboard to go back to the previous page, they'd have to click outside the form field to remove the focus from the form element to be able to use their Backspace key. The Back button on the browser menu is unaffected since clicking it will automatically remove the focus from the form element.
  • Causing an event to happen may conflict with other code. Check that everything works correctly with Internet Explorer and Firefox before implementing this technique live on your web site. At the time of this writing it's no longer necessary to check things in Netscape since Netscape now uses either the Firefox rendering engine or Internet Explorer rendering engine, depending on which the user sets as his or her preference.
Okay, so it's not as good a trick as being able to turn invisible or having x-ray eyes, but still, it might come in handy sometime.
Back | Web Design Tutorials Index

Ezine for Webmasters

Bookmark and Share

Almost a Newsletter

Changing list hosts. Will post a new subscribe form shortly.

Did you know...

The member's site has about 100 standards compliant HTML and CSS tutorials, 31 handy reference charts, reprintable content, web graphics, exclusive fonts, free software, free ebooks and more? All this for less than 9 cents a day! [ Details ]
See my fancy bottom! :)