Jon
Rohan

I'm a front end web developer living in San Francisco. I have been coding HTML since I was 15. I strive to be the best I can at what I do. I believe in clean and simple design as well as code. This is where I represent myself on the web. I am always looking to form relationships with other amazing people, part time or full time. contact me!

jQuery Ghost Textbox plugin

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.

Tags: , , , , 24 Jul 2009

About the Author, Jon Rohan

Hey! Thanks for stopping by. I love posting new topics here about various development things. If you liked it follow me on twitter and let me know.

Subscribe to Posts

2 comments

Add comment