Demo this script here.
I'm seeing more and more sites using a simple little text box effect. The text box in a form is loaded with some descriptive text in it like "Name" and when the user clicks on it, the box empties itself in readiness for input. It's a nice little effect that makes forms look cleaner so I thought I'd put up a code snippet here that does it for you.
function textboxFocus( txtBox )
{
var tempVal = txtBox.value;
txtBox.value = '';
txtBox.onfocus = null;
txtBox.onblur = function() { textboxBlur( txtBox, tempVal ); };
}// End function textboxFocus
function textboxBlur( txtBox, msg )
{
if( txtBox.value.length == 0 )
{
txtBox.value = msg;
txtBox.onfocus = function() { textboxFocus( txtBox ); };
txtBox.onblur = null;
}// End if
}// End function textboxBlur
Now, here's how to use that code: Obviously, the first thing you need to do is to copy the above code into your document. Next, you'll need a textbox with an onFocus event set up to call textBoxFocus:
<input type="text" name="myText" value="Name" onFocus="textboxFocus( this );" />
Now, when the page loads, the textbox will have whatever text you put into the value attribute (in this case 'Name'.) When the user's cursor enters the textbox, the onFocus event fires off and textboxFocus is called.
The textboxFocus function removes the default text, removes the onFocus event handler (so the user's text won't be blanked out), and sets up an event to fire onBlur to call textboxBlur with the original text as an argument.
When textboxBlur is called it checks to see if the user entered anything. If not, it puts the default text back in and sets up the original event handler to fire onFocus to call textboxFocus.
I think this is a nice script cause its small (only 17 lines), simple (only 2 functions), it works on textarea elements too, and it puts the original text back into the box if the user doesn't enter anything.
Home