jquery-watermark


jQuery plugin adds watermark capability to HTML input elements

Watermark plugin for jQuery

Version 3.2.0

Compatible with jQuery 1.2.3+

Dual-licensed under the MIT or GPL2 licenses.

Contents

Introduction

Using the Plugin

Important Usage Notes

Static Properties and Methods

Troubleshooting

Watermark does not ever appear
Watermark only appears in gray text
Watermark appears in regular-styled text (not light gray text)
Can't enter the same text as the watermark
Using the Watermark and Validate plugins on the same elements

About the Author

http://jquery-watermark.googlecode.com/svn/trunk/jquery-watermark/wiki/icon-download-green-32.png' align='center' border='0' width='32' height='32' /> http://jquery-watermark.googlecode.com/svn/trunk/jquery-watermark/jquery.watermark-3.2.0.zip'>Download the latest version (3.2.0)

http://jquery-watermark.googlecode.com/svn/trunk/jquery-watermark/wiki/icon-new-32.png' align='center' border='0' width='32' height='32' /> http://jquery-watermark.googlecode.com/svn/trunk/jquery-watermark/wiki/changelog.txt'>See latest change log

Note: Because Google has disabled the ability to create new downloads on the Download page, the Download page only contains versions prior to release 3.2.0, and will not be updated. All versions will continue to be archived and available for download in the Source tab.

Introduction

This simple-to-use jQuery plugin adds watermark capability to HTML input and textarea elements.

A watermark typically appears as light gray text within an input or textarea element whenever the element is empty and does not have focus. This provides a hint to the user as to what the input or textarea element is used for, or the type of input that is required.

For example, a search input space sometimes appears at the top of the page, giving the user quick access to the search functionality. Oftentimes you will see the word "Search" in light gray text in that space, and when the user clicks into the entry space, the word disappears. That is an example of a watermark.

http://jquery-watermark.googlecode.com/svn/trunk/jquery-watermark/wiki/sample-watermark.png' />

This plugin lets you specify the text that will be used for the watermark, and optionally you can supply your own CSS class name that will be applied to the input or textarea element every time the watermark is shown.

If you do not supply your own class name, the class name "watermark" is used.

Other important features include:

  • Allows you to change the watermark text and/or class name any time after the watermark is initialized. One of the examples included with the plugin demonstrates this capability by showing a watermark that doubles as a countdown timer.
  • Capable of displaying a watermark in password input elements, showing the watermark in plain text, but then switching to password-protected (obscured) mode when focused. (Because of the complexity of making password watermarks operate, it is recommended that programmatic changes to password input elements be avoided.)
  • The plugin can also handle input elements of type="search" (WebKit browsers).
  • Supports HTML5 "placeholder" capabilities natively (in browsers that support it), or native support can be disabled so that the plugin controls all watermarks. (Watermarks are referred to as "placeholders" in HTML5.)
  • Supports drag-and-drop to watermarked elements. Drag-and-drop support is significant, because it is currently supported by few (if any) jQuery plugins. Combined with the Watermark plugin's ability to support native browser watermark features, this may be the most feature-complete watermark plugin available.
  • Enhances the native jQuery .val() function so you can use .val() directly to get and/or set an element's value.
  • New for version 3.2, the plugin can set watermarks based on attribute values, so you can use placeholder attributes on input elements, using the plugin to add support for older browsers.

Using the plugin

To set a watermark of "Required information" on an input element, you would use a line of code such as:

   $( '#inputId' ).watermark( 'Required information' );

If you want to use a different class name to define the appearance of the watermark, simply add the class name to the options specified in the second argument:

   $( '#inputId' ).watermark( 'Required information', { className: 'myClassName' } );

If you want to avoid using native browser support (for example, for Search elements that have buggy drag-and-drop support in WebKit), add the useNative option to the options specified in the second argument, as follows:

   $( '#inputId' ).watermark( 'Search', { useNative: false } );

New for version 3.2, you can set watermarks using the content of an attribute. For example, to use the placeholder attribute for native support in modern browsers, with the plugin providing support for older browsers, you can use one line of code such as the following. (When using the textAttr option the watermark string argument is optional.)

   $( ':text' ).watermark( { textAttr: 'placeholder' } );

The textAttr option can be set to the name of any attribute, so (for example) you could use the title attribute by using textAttr: 'title'. When using textAttr to set watermarks, if the specified attribute does not exist on an element, no watermark is set on that element.

Important usage notes

  • Multiple input elements - You can set multiple input elements to the same watermark at once by including them all in the jQuery matched set. For example, you can let the user know which input is optional by setting a watermark based on class name:
       $( 'input.optional' ).watermark( 'Optional' );
    
  • Non-relevant elements ignored - The plugin ignores any elements in the matched set that are not input elements of type="text/password/search" and not textarea elements, so you do not have to filter your matched set to remove extra elements.
  • Return value - When watermark(...) is called on a matched set, it returns the same matched set, allowing you to chain the plugin.
  • No longer necessary as of version 3.1! Now you can use .val() to get and/or set an element's value, and all the plumbing is handled automatically for you. Programmatic changes - JavaScript events do not generally respond to programmatic changes in an input element's value, so you will need to manually refresh the watermark after you change the value through code. When calling the plugin for the purpose of a refresh, do not include any arguments. An example of changing the value, followed by a watermark refresh, would be:
    {{{
    $( '#myInput' ).val( 'newValue' ).watermark();
    }}}
  • Avoid programmatic changes to passwords - Because of the complexity of making password watermarks operate, it is recommended that programmatic changes to password input elements (changes made after the page finishes loading) be avoided.
  • Mutli-line textarea watermarks - In textarea elements, you can create multi-line watermarks by specifying a line-break character ( \n ) where each new line should start.
  • Form submission - New functionality in version 3.2 - Prior to version 3.2 the plugin would automatically clean up all watermarks on the page prior to form submission. As of version 3.2 the plugin will only clean up watermarks within the form being submitted, so if you have additional forms on the page the watermarks in those other forms will not disappear when submitting the page. If you set the option clearAllFormsOnSubmit to true, the old behavior of cleaning up all watermarks on the page prior to submission will be performed.
  • Dynamic changes to watermark text and/or class - After a watermark is initialized, you can continue to make changes to it, changing the text, the class name (style), or both. The plugin demo page included in the download package demonstrates a watermark that doubles as a countdown timer. As the timer nears zero, the style changes to red text.

Static properties and methods

The plugin includes static properties and methods that are called in a "stand-alone" manner (not on a matched set). Many developers will never need to use any of these properties or methods, but they exist in case you need them.

Any time < selector > is indicated, you can pass any valid jQuery selector, such as a DOM element, selector string, jQuery matched set, an array of elements, etc.

$.watermark.options

Examples
   $.watermark.options.className = 'myClass';


$.watermark.options.useNative = false;

$.watermark.options.useNative = myFunction;

$.watermark.options.hideBeforeUnload = false;

$.watermark.options = {
className: 'myClass',
useNative: false,
hideBeforeUnload: false
};
Description You can control the default class name to use for watermarks, as well as if native browser support for watermarks should be used. Both values can be overidden for individual watermarks.
The hideBeforeUnload option can be set to false to disable the automatic hiding of watermarks during the beforeunload event. It is a global option that determines the behavior of all watermarks on the current page. The option is not evaluated until the beforeunload event takes place, so the option can be set at any point before that. The default value for this option is true.
If you try to set hideBeforeUnload by passing the option to the .watermark() function, it will have no effect, because it is a global option. You must define the option by setting it as follows:
   $.watermark.options.hideBeforeUnload = (true | false);

$.watermark.show( )

Example
   $.watermark.show( 'input.optional' );

Description The equivalent of calling .watermark() (with no arguments) on a matched set, this method "refreshes" all matched elements.

$.watermark.hide( )

Example
   $.watermark.hide( '#myInput' );

Description Removes the watermark from all matched elements. This does not completely destroy the watermark definition, so if after calling this method the user enters and leaves the element, the watermark will re-activate.

$.watermark.showAll()

Example
   $.watermark.showAll();

Description This method "refreshes" all watermarks on the page. Maybe use useful after several programmatic changes were made to input values.

$.watermark.hideAll()

Example
   $.watermark.hideAll();

Description Removes all watermarks from the page. This method is called automatically just before form submission to "clean up" all watermarks, and ensure that watermark text is not submitted to the Web server. After calling this method, a watermark will re-appear if the user enters and then leaves an input element that previously contained a watermark.

Troubleshooting

Watermark does not ever appear

Check the following:

  • Verify you are using the right syntax:
       $( < selector > ).watermark( < text > [ , < options > ] )
    
  • Be sure the first argument includes a valid string, and that the string is not empty.
  • Are you certain that your jQuery selector matched one or more input elements? You can quickly test if your selector is matching elements by temporarily inserting an alert() call into your code. If a zero (0) is displayed in the alert box, you know that it did not match any elements.
       alert( $( < selector > ).length );
    
  • The plugin only places watermarks on input elements with type="text/password/search" and on textarea elements. Are you sure that you are matching the correct input element(s) and/or textarea(s)? For example, you cannot use a watermark on an input element with type="checkbox".

Watermark only appears in gray text

This plugin uses native browser watermark abilities if they are available. For example, in Safari and Google Chrome, text input tags have built-in watermark abilities using the placeholder property. Currently the use of placeholder always renders gray text.

To override the use of native browser support for watermarks (placeholders), use the $.watermark.options.useNative = false option described above.

EXPERIMENTAL: All modern Web browsers contain non-standard ways of styling placeholders (native watermarks). Until there is an official W3C standard for styling placeholders, you'll need to keep an eye on this and adjust your code as browsers refine their placeholder styling features.

  • WebKit and Blink (Safari, Google Chrome, Opera 15+):
       input::-webkit-input-placeholder {
    
    color: #f00;
    }
  • Firefox (version 4 to 18):
       input:-moz-placeholder {
    
    color: #f00;
    opacity: 1; /* FF sets opacity to 0.54 by default */
    }
  • Firefox (version 19+):
       input::-moz-placeholder {
    
    color: #f00;
    opacity: 1; /* FF sets opacity to 0.54 by default */
    }
  • Internet Explorer (version 10+):
       input:-ms-input-placeholder {
    
    color: #f00;
    }

Note: In the style definition for Firefox above we have set the opacity to 1 because Firefox (unlike other browsers) automatically sets the opacity of placeholders to 0.54 by default.

User agents are required to ignore a rule with an unknown selector, so you need to separate the rules for each browser in your CSS. Otherwise the whole group would be ignored by all browsers, and you would see a regular gray watermark.

So until a W3C standard is implemented, you cannot include a definition like the following.

input::-webkit-input-placeholder,

input:-moz-placeholder,
input:-ms-input-placeholder {
color: #f00;
}

Instead, you need three separate CSS definition blocks, one for each browser -- even though they will in all likelihood be made up of the same styles.

Reading the element's value property gets the watermark, not the value

To get or set the value of a watermarked element (the value that the user enters), use the jQuery .val() function, not the value property of the element directly. For example:

// Set the value

$( '#myElement' ).val( 'John Doe' );

// Get the value
alert( $( '#myElement' ).val() );

Watermark appears in regular-styled text (not light gray text)

Don't forget that you need to define the CSS style for the watermark, either in an external style sheet, or within the page itself (in style tags).

If you are using the default class name (not specifying a className property in the second argument), you will need to define the watermark style using the class name watermark. For example:

<style type="text/css">

.watermark {
color: #999;
}
</style>

If you specified the className property in the second argument, be sure that you have defined the watermark styles using that class name.

Another common cause is a CSS cascade problem, where your style definition is overridden by another definition with a higher level of specificity.

In the following example, the watermark style would appear as black text, even though the gray color is defined after the black definition:

<style type="text/css">

input[type=text] {
color: #000;
}
.watermark {
color: #999;
}
</style>

Even though the definition containing the gray color (#999) appears after the definition with the black color (#000), the watermark text will still be black. That's because the first definition has a higher level of specificity, according to CSS rules, than the second definition.

A sure-fire way to be sure this doesn't happen is to use !important on your watermark definitions, like so:

<style type="text/css">

.watermark {
color: #999 !important;
}
</style>

Can't enter the same text as the watermark

What if you want the user to be able to enter the exact same text as a watermark? For example, your search box has the watermark "Search", and the user wants to search for the term "Search".

Normally, once the user enters "Search", the plugin recognizes the text as a watermark, and applies the watermark style.

One easy way around this is to use a watermark that contains spaces after the text. So in the case of the search box, you could use
"Search      " instead of "Search".

The user can't see the spaces, but internally they distinguish the watermark in a way that the user is unlikely to stumble across.

Using the Watermark and Validate plugins on the same elements

If you find that your form validation is failing because the watermarks are not being cleared before validation occurs, then you need to adjust the order in which you set up the watermarks and validation.

The proper order is to always set up watermarks before anything else -- especially before validation. That's because jQuery carefully controls the order of events during form submission, and calls them in the order they were set up. If you set up validation first, then the form will be validated before the watermarks are cleared.

Setting up watermarks and validation in the proper order is as simple as placing the lines of code in the correct order, like in the following example:

$( '#myElement' ).watermark( 'Required' );

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

Also, it is recommended that you specify a $.watermark.showAll() call to be triggered every time form validation fails. By doing so, you will ensure the watermarks re-appear when validation fails.

For example, using the jQuery Validation plugin (available at http://bassistance.de/jquery-plugins/jquery-plugin-validation/'>http://bassistance.de/jquery-plugins/jquery-plugin-validation/), you would change the above example as follows:

$( '#myElement' ).watermark( 'Required' );

$( '#myForm' ).validate( { invalidHandler: $.watermark.showAll } );

About the author

Todd Northrop is the owner and developer of Lottery Post (http://www.lotterypost.com/'>www.lotterypost.com), the world's largest community of lottery players and home to the #1 lottery results service worldwide.

He founded his technology company, Speednet Group (http://www.speednet.biz/'>www.speednet.biz), in 2000.

Todd was featured in Microsoft's (http://www.asp.net/ajax/showcase/interview/default.aspx?as=28'>ASP.NET AJAX Showcase).

Project Information

Labels:
jQuery plugin watermark JavaScript placeholder input textarea