Created
July 7, 2010 05:09
-
-
Save juliocesar/466329 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
// Could swear I shared this before, but here it goes again... | |
// $.ghost | |
// 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) { return this.each(function() { $.ghost(this, label, options) }) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment