JQuery Filler-Text Function

Taking a work-related break to share a bit of code with ya’ll. It’s a JQuery filler-text function (or grey-out function). What’s that? It’s just something that’ll make it easy to put that replaceable grey text in a form field.

The problem:

I want to pre-load a text-field with a value, e.g. “User Name…” for some reason or another. But, that value has to disappear when the user clicks on that field, and it has to reappear if the user clicks away while leaving the form empty.

Subtle addition to the problem: the field can’t have the filler text when the form is submitted.

Right now the function only works on input elements and not textareas. E.g., <input type=’text’ name=’user_name’ />.

Here’s an example usage for the above field:

$(‘input[name|=”user_name”]’).greyout(‘User Name…’);

You’ll be able to see this in action when my new design pops up on realcompliments.com and its ilk.

Another way to use the function is on an input field like so: <input type=’text’ name=’user_name’ value=’User Name…’ />

$(‘input[name|=”user_name”]’).greyout();

It returns itself so it’s chainable, e.g. $(‘input’).greyout().addClass(‘pineapples’);

To use it, declare a css class called fade-color (.fade-color { color:#909090; }) and include the js after jQuery.

Enjoy irresponsibly.

jQuery.fn.extend({
 greyout: function (original_value) {
 if (original_value == undefined) {
 original_value = $(this).attr('value');
 }
 var current = $(this);
 if ($(this).attr('value') == '') {
 $(this).attr('value',original_value);
 }
 if ($(this).attr('value') == original_value) {
 $(this).addClass('fade-color');
 }
 $(this).blur(function() {
 if ($(this).attr('value') == '') {
 $(this).attr('value',original_value);
 $(this).toggleClass('fade-color');
 }
 }).focus(function() {
 if ($(this).attr('value') == original_value) {
 $(this).attr('value', '');
 $(this).toggleClass('fade-color')
 }
 });

 $(this).closest('form').submit(function() {
 if (current.attr('value') == original_value) {
 current.attr('value','');
 }
 });
 return current;
 }
});

Leave a Comment

Your email address will not be published. Required fields are marked *