Created
April 1, 2012 02:46
-
-
Save ShaunSpringer/2270821 to your computer and use it in GitHub Desktop.
jQuery default text for text input fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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