Title-Based Textbox Hints

Time to rethink my old method of displaying textbox hints with background images. That method still works fine for compact login forms, but what if we have several textboxes on a page with different hints that may need changing. I don’t want to have to create/maintain images for each textbox hint, so I’d rather use text. Where should I get that text from though? I could use the label text, but sometimes that needs to be different from the hint. Take this search field for instance:

Textbox Hint Example

The label here would be “Search:”, but in the hint I want to give the user some examples of data they can search for. A great place to put this hint information is the title attribute of the textbox. For users without JavaScript, hovering an input with a title will show them a tooltip of the hint. Using jQuery though, we can enhance the experience quite a bit:

$('input.txbhint').focus(function() {
	if ($(this).val() == "" || $(this).val() == $(this).attr('title')){
		$(this).val("").removeClass("hinted");
	}
}).blur(function() {
	if ($(this).val() == "") {
		$(this).val($(this).attr('title')).addClass("hinted");
	}
}).filter(function() {
	if ($(this).val() == "" || $(this).val() == $(this).attr('title')){
		$(this).val($(this).attr('title')).addClass("hinted");
	}
});

The jQuery code above simply sets the input’s title text as it’s value and colors it gray (via the “hinted” class) until the user focuses on it. When they do, the value gets removed and the text color gets set to black. If the user leaves the textbox and the value is still blank, we cleverly reset the text with the title text again and change the color back to gray.

View the Demo


About this Entry