Created
September 17, 2009 04:10
-
-
Save juliocesar/188340 to your computer and use it in GitHub Desktop.
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
// 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