Jory Cunningham

Developer

This is where I archive useful code snippets and musings about web development. The content of the blog does not necessarily reflect the opinions of my employer or our clients. Have comments about any of this? Find me on Twitter (@oryjay).

Watermarkerupper: A Simple jQuery Plugin for Watermarked Input Labels

This is a simple jQuery plugin for creating "watermarked" labels for input fields and text areas. It will affect all text inputs, and text-style inputs (password and all of the new HTML5 input types that are text based) as well as text area tags.

The goal of this plugin is to make an easy-to-use, lightweight plugin that encourages accessibility standards.

For password input types, the plugin creates a dummy text input to house the watermarked label dynamically switches the input between this dummy field and the actual password inout on focus/blur. This is done to get around the inability to change an input type through jQuery.

Read on to get the plug-in...

Download from GitHub

The plugin will use the content of the label tag associated with the field for the watermarked label and will hide the label itself. To avoid the flash of the labels before the JS hides them, you should also hide the labels with CSS.

Example:

The association is made first through matching the label's "for" attribute to the "name" attribute of the input. If that fails, the plugin will then look for the immediately preceding label in the document.

On load, the labels tags are hidden and the value of each field becomes the label value. On focus, the label value is removed for data input and the field is given a class of "activeField" (this can be changed in options).

On blur, the plugin checked to see if the field was filled. If so the "activeField" class is replaced with 'filledField', if not the original watermark field returns and the "activeField" class is removed.

Initialization

Attach the .watermarkerupper() function to the form or other containing div, the inputs of which you would like to affect.

 $('#myForm').watermarkerupper();

Options

The following options can be passed to the function:

activeClass: (text string) This will be the class name assigned when the field has focus (default: 'activeField').

filledClass: (text string) This will be the class name assigned when the field has lost focus and has been filled out (default: 'filledField').

pwordDisplay: (any valid value of the CSS 'display' property) this controls the 'display' CSS applied to the dummy field created for using this plug in with password fields (default: 'inline').

Example

   $('#myForm').watermarkerupper({
        'activeClass' : 'myActiveclass',
        'filledClass' : 'myFilledclass',
        'pwordDisplay' : 'block'
    });

Download from GitHub

Burrito Enthusiast