Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created September 17, 2009 04:10
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 juliocesar/188340 to your computer and use it in GitHub Desktop.
Save juliocesar/188340 to your computer and use it in GitHub Desktop.
// Oh, by the way, it works like this:
//
// $('myform :text:first').ghost('username');
//
// The above will make the first text element of a form display a
// slightly faded "username" text inside until focused.
$.ghost = function(element, label, options) {
if (typeof options == 'undefined') options = {};
var originalColor = $(element).css('color');
var originalStyle = $(element).css('font-style');
function ghostify(element) {
if (touched(element)) return false;
$(element)
.css('color', (options.color || '#ccc'))
.css('font-style', (options.italic == false ? (originalStyle || 'normal') : 'italic'))
.val(label)
}
function deghostify(element) {
if ($(element).val() != label) return false;
$(element)
.css('color', originalColor)
.css('font-style', originalStyle)
.val('')
}
function touched(element) {
return ($(element).val() != '' && $(element).val() != label);
}
$(element).focus(function() { deghostify(this) });
$(element).blur(function() { ghostify(this) });
$(element).parents('form').submit(function() { if (!touched(element)) deghostify(element) });
ghostify(element);
}
$.fn.ghost = function(label, options) {
this.each(function() {
new $.ghost(this, label, options);
return this
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment