Sunday, December 13, 2009

jQuery Watermark Plugin

The following code was adapter from Very simple textbox watermark using JQuery and converted into a reusable jQuery plugin.

Given the following text box

<input type="text" id="textBox1" class="watermarkOn"
title="Type here" value="Type here" />

Add the following CSS style:
<style type="text/css">
.watermarkOn {
color: #CCCCCC;
font-style: italic;
}
</style>


jQuery Plugin Code

(function($) {
$.fn.extend({
//plugin name - watermark
watermark: function(options) {

//Settings list and the default values
var defaults = {
css: 'watermarkOn',
tag: 'title'
};

var options = $.extend(defaults, options);

return this.each(function() {
var o = options;

// When the textbox comes under focus:
// 1. Remove the watermark class and
// 2. clear the text box
$(this).focus(function() {

$(this).filter(function() {
//We only want this to apply if
//nothing was actually entered
return $(this).val() == "" ||
$(this).val() == $(this).attr(o.tag)

}).removeClass(o.css).val("");

});

// When the textbox loses focus:
// 1. Add the watermark class and
// 2. Set the default text
$(this).blur(function() {

$(this).filter(function() {
//We only want this to apply if
//nothing was actually entered
return $(this).val() == ""

}).addClass(o.css).val($(this).attr(o.tag));

});

});
}
});
})(jQuery);


Add the following lines to your document.ready function.
$(document).ready(function() {
$("#textBox1").watermark({css:"watermarkOn",tag:"title"});
});