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.
I am a developer (okay... that's very obvious!). I started programming at the age of 17 when I entered my engineering graduation back in the year 2001. I started off with C, C++ on UNIX. But soon I realized that if I need to make money out of my skills, I need to add some visual element to my applications (and that I need to switch to MS technologies!). Someone told me about VB. I started learning it but couldn’t get thru (I was religiously in love with curly braces; I never felt VB is a language). Then I began with VC++ 6.0 and I fell in love with it. Since then, I have been working on various MS technologies (C++, C#, VB.NET, SQL Server 2000/2005 etc.) I graduated in 2005 and currently, I am working with Microsoft in Hyderabad, India.
That’s all I can write as of now. If you want to know more, drop me a mail, I will try and respond