On many sites you’ll often see a code hint in text input areas showing you how to format your text, or just as a way to inform you want belongs there.
There are a couple different ways to do this. You can do just simple javascript within the ‘onfocus’ and ‘onblur’ like this:
<input id="username" name="username" size="25" type="text" value="User Name" onfocus="if (this.value == 'User Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'User Name';}" />
But this makes your html look ugly and messy. So let’s stick it in a separate JS file. First i’ll show it using the Prototype framework:
$('username').setStyle({color:'#666'}); $('username').value = 'User Name'; $('username').observe('focus', function() { if (this.value == 'User Name') { this.value = ''; this.setStyle({color:'#000'}); } }); $('username').observe('blur', function() { if (this.value == '') { this.value = 'User Name'; this.setStyle({color:'#666'}); } });
First we set the initial value for the input field and change the color. Then, we add the listener to watch for a change. Notice we have a couple of if statements in there, we only want to clear the value if the user has not typed something in.
Or, here it is in JQuery:
$("#username").val("User Name") .css("color", "#666666"); //Show Hide when focus/unfocus $("#username").livequery(function() { $(this).focus(function() { $(this).val("") .css("color", "#000000"); }); $(this).blur(function() { $(this).val("User Name") .css("color", "#666666"); }); });
Edit: You’ll notice the LiveQuery tag in my JQuery snippet, that plugin can be found here:http://plugins.jquery.com/project/livequery
And there we go, 3 ways to change text input fields!
thanks http://www.letstalkweb.net/2009/02/05/javascript-text-hints-in-input-fields/