Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Watermark TextBox using JavaScript

Posted by Viral Sarvaiya on July 11, 2009

<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);")


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: