Created
March 28, 2010 17:13
-
-
Save davegurnell/346878 to your computer and use it in GitHub Desktop.
Text field placeholders with jQuery.
This file contains 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
/* 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