Skip to content

Instantly share code, notes, and snippets.

@ShaunSpringer
Created April 1, 2012 02:46
Show Gist options
  • Save ShaunSpringer/2270821 to your computer and use it in GitHub Desktop.
Save ShaunSpringer/2270821 to your computer and use it in GitHub Desktop.
jQuery default text for text input fields
/**
* DEFAULT TEXT
* Written by Shaun Springer
* Free to use, distribute, and modify.
*
* Example:
* $('input[type="textarea"]').defaultText();
*
* jsFiddle: http://jsfiddle.net/Springerlax11/wWCr8/
*/
(function($){
$.defaultText = function(element, options)
{
var defaults = {
'focusClass' : 'default',
'defaultText' : 'Default text'
};
var plugin = this;
plugin.settings = {};
var $element = $(element);
var element = element;
plugin.init = function()
{
// Create some defaults, extending them with any options that were provided
plugin.settings = $.extend({}, defaults, options);
$element.bind('focus', focusEvent)
.bind('blur', blurEvent);
$element.addClass(plugin.settings.focusClass);
$element.val(plugin.settings.defaultText);
}
var focusEvent = function(e)
{
$element.removeClass(plugin.settings.focusClass);
if ($element.val() == plugin.settings.defaultText)
{
$element.val("");
}
}
var blurEvent = function(e)
{
if ($element.val() === "")
{
$element.val(plugin.settings.defaultText);
$element.addClass(plugin.settings.focusClass);
}
}
plugin.init();
}
$.fn.defaultText = function(options)
{
return this.each(function() {
if (undefined == $(this).data('defaultText')) {
var plugin = new $.defaultText(this, options);
$(this).data('defaultText', plugin);
}
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment