Thursday, 8 January 2009

jQuery watermark plugin

Here is a jQuery plugin for adding a watermark effect to elements (e.g. text box):

(function($) {
// The element that has focus (or null when nothing has focus).
var inputFocus = null;

// This keeps track of the element that has focus.
$(":input").focus(function() {
inputFocus = this;
}).blur(function() {
inputFocus = null;
});

$.fn.hasFocus = function() {
return this.attr("id") == $(inputFocus).attr("id");
}
})(jQuery);

(function($) {
var watermarkDefaults = {
watermarkedClass: "input-watermarked",
watermarkedText: ""
};

$.fn.watermark = function(settings) {
settings = $.extend({}, watermarkDefaults, settings);

var self = this;

self.addWatermark(settings);

if (self.isWatermarked(settings)) {
settings.watermarkedText = self.val();
}

self.focus(function() {
self.removeWatermark(settings);
});

// This might be an expensive exeucution!?
// Added to prevent strange behaviour when the user
// sets the focus before everything has fully loaded.
self.keydown(function() {
self.removeWatermark(settings);
});

self.blur(function() {
self.addWatermark(settings);
});

// Clear the watermark text when the form is submitted.
self.parents("form:first").submit(function() {
self.removeWatermark(settings);
});
}

$.fn.addWatermark = function(settings) {
settings = $.extend({}, watermarkDefaults, settings);

if (!this.hasFocus() && (this.val().length === 0 this.val() === settings.watermarkedText)) {
this.addClass(settings.watermarkedClass);

this.val(settings.watermarkedText);
}
}

$.fn.isWatermarked = function(settings) {
settings = $.extend({}, watermarkDefaults, settings);

return this.hasClass(settings.watermarkedClass)/* && this.val() === settings.watermarkedText*/;
}

$.fn.removeWatermark = function(settings) {
settings = $.extend({}, watermarkDefaults, settings);

if (this.isWatermarked(settings)) {
this.removeClass(settings.watermarkedClass);

this.val("");
}
}
})(jQuery);

Examples:

$(function(){
$("#id1").watermark({
watermarkedClass: "custom-input-watermarked",
watermarkedText: "Click here..."
});
});

$(function(){
$("#id2").watermark({
watermarkedText: "Click here..."
});
});

3 comments:

Greg said...

Andrew,

Thanks a lot for sharing this plugin, but unfortunately I noticed that your examples don't work with the code you provided.

You reference a non-existent setting 'watermarkedText' in the examples, but it should be plain 'text' for it to work.

So it would be great if you could either change your examples, or change your plugin code.

But this is a minor quibble, thanks for sharing your work!

Andrew Gunn said...

Hi Greg,

Cheers for the comment on the watermark plugin. I'll update the code later today. Nice spot!

Anonymous said...

similarly, should be className instead of watermarkClassName