Introduction
You may have seen some web sites displaying watermarks in text boxes. As soon as you click on a text box, the watermark disappears and you can start entering text.
In this article, I will explain a small JavaScript trick that you can use to do the same in your web application. I have included a library that you can use to achieve
the same functionality without having to worry about writing JavaScript code.
Background
The idea is to capitalize on the OnFocus
and OnBlur
events of the HTML
input
tag. The library sets flips between two styles for the input
tag and, also, it checks if the default text has been changed or not.
Using the code
To use the code, you need to provide at least two styles for the text box. One that represents the watermarked textbox and another that represents a normal textbox.
The sample project includes such a stylesheet.
To apply watermark to a textbox with id=textbox1
, write the following in your page_load
event handler:
TextBoxWatermark.WaterMarkHelper.ApplyWaterMarkToTextBox(textBox1, _
"Watermarktext", "WaterMarkedTextBoxStyle", "NormalTextBoxStyle")
Enhancements
You can enhance the library to intercept the submit event and remove the default text before the required field validators fire.
Update history
- August 30, 2006: Patched the single quote bug. The library used to break down when a single quote was supplied in
WatermarkText
. - August 23, 2006: Patched the library to work with Firefox.