Have you ever wanted to provide forms with default values or examples to improve user experience? Here’s how you can do it in an easy, re-usable way using a jQuery plugin called valueFx.

This is a more agile, re-usable version of the Focus & Blur effects I’ve previously posted about. This can be used on as many text <input>’s as you like, simply by adding class=”valueFx” to the tag.

For a better explanation of what this is visit the Search Field Focus & Blur Effects post.

XHTML

JavaScript / jQuery Plugin

jQuery.fn.valueFx = function() {
	return this.each(function(){
		var $field = $(this);
		var $value = $(this).val();
		var $newVal;	
		$field.addClass('placeholder');
		$field.focus(function(){
			if($field.hasClass('valueFx')){
				if (($value == '') || ($value == $value)) {
					$field.removeClass('placeholder').addClass('focus').val('');
					$newVal = $(this).val();
				}
			}
		});
		$field.blur(function(){
			$newVal = $(this).val();
			if ($newVal == '') {
				$field.val($value).removeClass('focus').addClass('placeholder');
			} else {
				$field.removeClass('placeholder').removeClass('valueFx');
			}
		});
	});
};

Simple Usage

$('input.valueFx').valueFx();

Above is the easiest way to setup this plugin. Of course, I prefer to add a little more logic to make things more intuitive.

Advanced Usage

if ($('input.valueFx').length > 0) {
	$.getScript('/path/to/jquery.valueFx.js',function(){
		$('input.valueFx').valueFx();
	});
}

What this does is first check to see if there are any input fields in the document that have a class of “valueFx“. If there are, we’ll load in the jquery.valueFx.js file, and run a function once it has been loaded. This function (or callback) runs the valueFx() method on all the input’s that have been found.

Download

jQuery Value Effects Plugin

Resources