I often work on sites that call for “ghost text boxes”. This is when a text box is already populated with words when the page loads. And then when the textbox is given focus the text goes away. Like This
I’ve seen a few ways to do this, explicitly writing a function that switches text, but this is too specific. This means that I’ll need to re-write this for every ghost text box on the site. Some people will add the functions in the onfocus and onblur attributes on the <input> tag. Same deal…
So I wrote this plugin to make my life simpler. How it works is, anytime you want a textbox to have ghost text you give it a placeholder attribute and put the ghost text inside. like so
<input type="text" class="ghost_text" placeholder="This is Ghost Text"/>
Then I just setup the ghost text globally.
$(".ghost_text").ghostText();
And we’re done! That was easy.
Here’s the plugin. It’s may not be perfect, and there are most likely hundreds of these on the net. But here is my implementation.
/* Copyright (c) 2009 Jon Rohan (http://dinnermint.org)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.0.0
* Written with jQuery 1.3.2
*/
(function($){$.fn.ghostText = function() {
return this.each(function(){
var text = $(this).attr("placeholder");
if(text!=""&&($(this).val()==""||$(this).val()==text)) {
$(this).addClass("disabled");
$(this).val(text);
$(this).focus(function(){
$(this).removeClass("disabled");
if($(this).val()==text) {
$(this).val("");
}
});
$(this).blur(function(){
if($(this).val()=="") {
$(this).val(text);
$(this).addClass("disabled");
}
});
}
});
};})(jQuery)
If you enjoyed reading this post, check out this post jQuery Auto-growing Textarea Plugin.
Hey Dude!! Really Like The Post. But When I Tried It Out, The GHOST BOX, Dos’nt seem To be Working For Me….. :( I Tried What U Said Word For Word But It Still Dos’nt Seem To Be Working For Me…. Google Chorme Seems To Show It Fine But It Dos’nt Work For Firefox And Internet Explorer.
if you don’t want your ghost text being submitted along with your form you can attach this script to your submit button:
$(“.submit”).bind(“click”, function(){
$(‘.disabled’).val(“”);
});