Skip to content

Instantly share code, notes, and snippets.

@davegurnell
Created March 28, 2010 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davegurnell/346878 to your computer and use it in GitHub Desktop.
Save davegurnell/346878 to your computer and use it in GitHub Desktop.
Text field placeholders with jQuery.
/* Text field placeholders
*
* Dave Gurnell, http://www.untyped.com
*
* Example usage: $("#my-date-field").placeholder("yyyy-mm-dd");
*/
(function ($) {
// -> Boolean
$.fn.hasPlaceholder = function () {
return $(this).data("placeholder") === true;
};
// String [String] -> jQuery
$.fn.placeholder = function (text, cssClass) {
return $(this).each(function () {
if(!text) {
throw "No text specified for placeholder.";
}
cssClass = cssClass || "placeholder";
var $this = $(this);
function onFocus () {
if($this.hasPlaceholder()) {
$this.val("").removeClass(cssClass).removeData("placeholder");
}
}
function onBlur () {
if($this.val() == "") {
$this.val(text).addClass(cssClass).data("placeholder", true);
}
}
$this.focus(onFocus).blur(onBlur);
onBlur();
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment