Many times people ask how to create a watermark effect on textbox using JavaScript.

Below is the short JavaScript that helps doing the same.


<script type = "text/javascript">

    var defaultText = "Enter your text here";

    function WaterMark(txt, evt)


        if(txt.value.length == 0 && evt.type == "blur")


   = "gray";

            txt.value = defaultText;


        if(txt.value == defaultText && evt.type == "focus")


   = "black";






The script will be called on onblur and onfocus events of the textbox. The script simply does the following two checks

1. If the textbox is empty and the event type is blur event it sets the watermark and changes the font color as Gray.

2. If the textbox text matches default text and the event type is the focus it clears the textbox and sets the font color as Black.


That’s all and just we now need to call it with the textbox.


<asp:TextBox ID="TextBox1" runat="server" Text = "Enter your text here"

    ForeColor = "Gray" onblur = "WaterMark(this, event);"

    onfocus = "WaterMark(this, event);">



As you will notice I am calling the same script on onblur and onfocus event and passing the reference of the textbox and the event object.

Visual Studio will throw warning when you call client side event in the above way. So if you do not want to get the warnings you can do in the following way from code behind.



TextBox1.Attributes.Add("onblur", "WaterMark(this, event);");

TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);");  



TextBox1.Attributes.Add("onblur", "WaterMark(this, event);")

TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);") 

You can test the above JavaScript here


Watermark TextBox    


The above JavaScript is tested in the following browsers

1.     Internet Explorer 7

2.     Firefox 3

3.     Google Chrome



You can download the complete the source here (2.08 kb)