Watermark Plugin

Cross-browser compatible Watermarks. Uses HTML5 specification if possible, and uses jQuery to simulate if not supported by the browser.

by Troy Alford

HTML

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

JavaScript

(function ($) {

   $.fn.Watermark = function (text, settings) {

      var defaults = {
         watermarkCss: {
            'color': '#AAA'
         },
         normalCss: {
            'color': ''
         }
      };

      var options = $.extend(true, {}, defaults, settings);

      var browserSupportsHtml5Placeholder = function () {
         var i = document.createElement('input');
         return 'placeholder' in i;
      }

      this.attr('placeholder', text);

      if (!browserSupportsHtml5Placeholder()) {
         // The text is set in the object already - but we must attach a handler to animate that text.
         this.unbind('focusin.Watermark focusout.Watermark')
         .bind('focusin.Watermark', function () {
            var $ph = $(this);
            if ($ph.val() === $ph.attr('placeholder')) {
               $ph.val('').css(options.normalCss);
            }
         }).bind('focusout.Watermark', function () {
            var $ph = $(this);
            if ($ph.val() === '' || $ph.val() === $ph.attr('placeholder')) {
               $ph.val($ph.attr('placeholder')).css(options.watermarkCss);
            }
         }).trigger('focusout.Watermark');
      }

      return this;
   };

})(jQuery);

$(function ($) {
    $('input').Watermark('enter text...', { 
        watermarkCss: { 'font-style': 'italic' }, 
        normalCss: { 'font-style': '' }
    });
})(jQuery);