How to: JavaScript help tip text in textboxes

Tuesday, September 9th, 2008

When I see search boxes I am often wondering which search parameters to enter. Am I searching for users of this site, or searching for content?

In comes help tips to the rescue! Help text placeholders are used often on search text boxes, but also on inputs which ask for a URL (eg. to remind users to prefix the link with http://).

or:

Here’s an simple function to do this using JavaScript:

1
2
3
4
5
6
7
8
9
10
function ToggleDefaultHelpText(obj, helptext, isFocus)
{
	var curr = obj.value.replace(/^\s+|\s+$/g, '') ;  // trim the text box's value
	var isEmpty = (curr.length < 1 || curr == helptext);
	obj.style.color = (isFocus) ? "#000000" : (isEmpty) ? "#999999" : "#000000";
	if (isFocus)
		obj.value = (isEmpty) ? "" : curr;
	else
		obj.value = (isEmpty) ? helptext : curr;
}

You will want your text box’s default state to be the same as the blur state, so execute the function with isFocus = false.

1
2
<input type="text" id="myTextBox" onfocus="javascript:ToggleDefaultHelpText(this, 'search user or tag', true);" />
ToggleDefaultHelpText(document.getElementById("myTextBox"), "search user or tag", false);

The better way to do this is to programmatically attach this function to the onfocus and onblur events of your text input. If you’re using MooTools it’ll be clean and simple – the above code turns into something much neater:

1
2
3
4
<input type="text" id="myTextBox" />
$('myTextBox').addEvent('focus', function() { ToggleDefaultHelpText($('myTextBox'), 'search user or tag', true); });
$('myTextBox').addEvent('blur', function() { ToggleDefaultHelpText($('myTextBox'), 'search user or tag', false); });
$('myTextBox').fireEvent('blur');  // execute the onblur function to initiate this text box

Hope this helps you to help your users.

leave a reply?