jQuery Plugin to Toggle Default Field Value on Focus and Blur
I can’t begin to count the number of times I have coded the same search field with the default value "Search…" in it and so that when the field receives focus, the text is cleared but magically reappears when the field blurs. Every time I code it I know I should save that snippet of code somewhere but it is always faster to just write it anew each time. Well, no more. I finally got around to writing jQuery plugin to allow me to add the focus/blur default value toggle to any field. I have very creatively named the plugin ‘Defaultify’.
The function call is about as simple as it gets:
$("#search-field").defaultify("Search...");
The function can be attached to any select which jQuery will recognize include element name, ID, Class or Object. The selector must, of course, refer to a field which can have a value to begin with.
The Source Code
The full code is not very complicated at all. In fact, it is about as basic as a jQuery plugin gets.
/**
* @name jQuery.defaultify
* @author Scott Lewis
* @url http://iconify.it
* @date August 16, 2011
*
* Adds a default value to a field or fields.
* The value will toggle on field
* focus and blur.
*/
(function($) {
$.fn.defaultify = function(defaultValue) {
/**
* Iterate through the collection of elements and
* return the object to preserve method chaining
*/
return this.each(function(i) {
/**
* Wrap the current element in an instance of jQuery
*/
var $this = $(this);
/**
* Set the initial value
*/
$this.val(defaultValue);
/**
* Do our kick-ass thing
*/
$this.focus(function(e) {
if ($.trim($this.val()) == defaultValue) $this.val("");
});
$this.blur(function(e) {
if ($.trim($this.val()) == "") $this.val(defaultValue);
});
});
};
})(jQuery);
That’s it folks. That is literally the entirety of the plugin.