Over a million developers have joined DZone.

Creating Hint/default Text In Javascript (RAW)

·
Basically, this chunk of code will cause a text box to have a default/hint text applied to it. When you click on the box the text will disappear, when you blur, the box should return to the default text if it is blank.

Usage:
createDefaultText( obj as object , defaultText as String , defaultTextColor as HexString );

Code:

function defaultText_focus(evt) {
	if (!evt) { evt = window.event; }
	var targ = getEventTarget(evt);
	if(targ.value.toLowerCase() == targ.defaultText.toLowerCase()) {
		targ.style.color = '';
		targ.value = '';
	}
}
			
function defaultText_set(targ) {
	if(targ.value.toLowerCase() == targ.defaultText.toLowerCase() || targ.value.length === 0) {
		targ.style.color = targ.defaultTextColor;
		targ.value = targ.defaultText;
	} else {
		targ.style.color = '';
	}
}
			
function defaultText_blur(evt) {
	if (!evt) { evt = window.event; }
	var targ = getEventTarget(evt);
	defaultText_set(targ);
}
			
function createDefaultText(obj, defaultText, defaultTextColor) {
	obj.defaultText = defaultText;
	obj.defaultTextColor = defaultTextColor;
	addEvent(obj, 'focus',defaultText_focus,false);
	addEvent(obj, 'blur',defaultText_blur,false);
	defaultText_set(obj);
}


Sample:
Uses code from
Event Target
Add Event



	
		
		Default Text Sample
		
	
	
	
		
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}