JQuery textbox watermark revisited: making it a plugin 5

In a previous post I talked about how you can do a textbox watermark very easily using JQuery. I’m long overdue in showing how you can take that same JQuery code and make it into a simple plugin.

So why would we make it a plugin? A JQuery plugin gives you the chance to encapsulate JQuery functionality into a single, pluggable module which can then be activated by calling a single method (with optional settings passed to it). If you’ve used things like the JQuery Validation library, you’ve seen a bit of the power of plugins. They are not hard to write, and the official documentation on the JQuery site gives you enough information to get started.

We will start off with the same basic HTML text box that we had in the previous post:

<input type="text" id="textBox1" />

And some simple CSS to go with it:

.watermark { color: #CCC; font-style: italic; }

So, just to recap what we want to do: when our focus is off of the textbox, and the textbox is empty, we want to display the default text, which is “type here…” in a light gray color. When the focus is on the textbox and the default text is displayed, we want to clear the box and the styling. If they type something in the box and then click elsewhere, we want to keep the new text and not reactivate the watermark style.

Using the previous JQuery code I posted as a base, here is the plugin code with comments to explain how it works:

(function($) {
	// Create a plugin with the name 'watermark'
	$.fn.watermark = function() {
		// Loop through the elements in the selector that we call the plug-in on
		this.each(function() {
			// Apply defaults to the box
			$(this).addClass("watermark").val("type here...");

			// Apply our focus and blur events
			// When we click on the field, we expect it to clear the field and remove the watermark
			$(this).focus(function() {
				$(this).filter(function() {
					// Check to see if we have a blank field or the default text
					return $(this).val() === "" || $(this).val() === "type here...";
				}).val("").removeClass("watermark");
			});

			// When we click off of the field, we expect it to replace the watermark,
			// unless we have entered text
			$(this).blur(function() {
				$(this).filter(function() {
					// Check to see if the field is blank
					return $(this).val() === "";
				}).addClass("watermark").val("type here...");
			});
		});
	};
})(jQuery);

To apply the plugin to our text box above we can now simply do this:

$(function() {
	$("#textBox1").watermark();
});

Making it better

What we’ve done so far is fine if you’re only concerned with a specific case, but what if we wanted to use this same plugin for different default text scenarios, or with different CSS classes? As it turns out, this is not hard to do.

We’re going to add two simple options to our plugin, but leave our defaults as they currently are:

(function($) {
	// Create a plugin with the name 'watermark'
	$.fn.watermark = function(settings) {
		// Defaults
		var config = {
			watermarkClass: 'watermark',
			defaultText: 'type here...'
		};

		// merge the passed in settings with our default config
		if(settings) $.extend(config, settings);

		// Loop through the elements in the selector that we call the plug-in on
		this.each(function() {
			// Apply defaults to the box
			$(this).addClass(config.watermarkClass).val(config.defaultText);

			// Apply our focus and blur events
			// When we click on the field, we expect it to clear the field and remove the watermark
			$(this).focus(function() {
				$(this).filter(function() {
					// Check to see if we have a blank field or the default text
					return $(this).val() === "" || $(this).val() === config.defaultText;
				}).val("").removeClass(config.watermarkClass);
			});

			// When we click off of the field, we expect it to replace the watermark,
			// unless we have entered text
			$(this).blur(function() {
				$(this).filter(function() {
					// Check to see if the field is blank
					return $(this).val() === "";
				}).addClass(config.watermarkClass).val(config.defaultText);
			});
		});
	};
})(jQuery);

Now, we can customize how we use the plugin:

$(function() {
	$("#textBox1").watermark({
		watermarkClass: 'grayText',
		defaultText: 'search'
	});
});

Files

Useful links

5 Comments so far

  1. Mikhail Diatchenko on June 6th, 2010

    If the default value is specified in the textbox it will be replaced by the watermark. Solution is to add the following line just above 16:

    if ($(this).val() == “”)

  2. Nik on November 9th, 2010

    This is a great post.. simple and small in size… I do have one issue. How do we make sure the watermark gets excluded from validation/form submission?

  3. payflow_charisma on January 13th, 2011

    thankyou for your script now i was make it be more easy :
    (function($) {
    // Create a plug-in with the name ‘watermark’
    $.fn.watermark = function(settings) {
    // Defaults
    var config = {
    watermarkClass: ‘watermark’
    };

    // merge the passed in settings with our default config
    if(settings) $.extend(config, settings);

    // Loop through the elements in the selector that we call the plug-in on
    this.each(function() {
    // Apply defaults to the box
    var val = $(this).attr(‘watermark’);
    $(this).addClass(config.watermarkClass).val(val);

    // Apply our focus and blur events
    // When we click on the field, we expect it to clear the field and remove the watermark
    $(this).focus(function() {
    return $(this).val(“”);
    });

    // When we click off of the field, we expect it to replace the watermark,
    // unless we have entered text
    $(this).blur(function() {

    return $(this).val(val);
    });
    });
    };
    })(jQuery);
    save that file with watermark.js and after that :

    $(function() {
    $(“.watermark”).watermark();
    });

    now to configure it in our textbox like this one:

    and for style :

    .watermark {
    color: #000;
    font-weight: bold;
    }

    once again thankyou for your share ^,^;

  4. payflow_charisma on January 13th, 2011

    sorry litle fix ..:
    (function($) {
    // Create a plug-in with the name ‘watermark’
    $.fn.watermark = function(settings)
    {
    // Defaults
    var config = {
    watermarkClass: ‘watermark’
    };

    // merge the passed in settings with our default config
    if(settings) $.extend(config, settings);

    // Loop through the elements in the selector that we call the plug-in on
    this.each(function() {
    var val = $(this).attr(‘watermark’);
    $(this).addClass(config.watermarkClass).val(val);
    $(this).focus(function() {
    $(this).filter(function() {
    // Check to see if we have a blank field or the default text
    return $(this).val() === “” || $(this).val() === val;
    }).val(“”);
    });
    $(this).blur(function() {
    $(this).filter(function() {
    // Check to see if the field is blank
    return $(this).val() === “”;
    }).addClass(config.watermarkClass).val(val);
    });

    });
    };
    })(jQuery);

  5. Jules Vasconez on March 18th, 2011

    Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your site? My website is in the exact same niche as yours and my users would really benefit from a lot of the information you provide here. Please let me know if this alright with you. Thanks a lot!

Leave a Reply