In this article I will explain with an example, how to add Watermark to an ASP.Net TextBox using JavaScript.
 
 
HTML Markup
The HTML Markup consists of:
TextBox – For capturing text.
The TextBox has been assigned with the JavaScript onblur and onfocus event handlers.
<asp:TextBox ID="txtName" runat="server" Text="Enter your text here" ForeColor="Gray" onblur="WaterMark(this, event);" onfocus="WaterMark(this, event);"></asp:TextBox>
 
 
Implementing Watermark TextBox using JavaScript
The Watermark JavaScript function can be implemented on the ASP.Net TextBox in the following ways.
Client Side
Inside the WaterMark function, two checks are performed as below:
1. If the TextBox is empty and the event type is blur, then it changes the font color as Gray and sets the default text.
2. If the TextBox text matches default text and the event type is focus event then, it clears the TextBox and sets the font color as Black.
<script type="text/javascript">
    function WaterMark(txt, evt) {
        var defaultText = "Enter your text here";
        if (txt.value.length == 0 && evt.type == "blur") {
            txt.style.color = "gray";
            txt.value = defaultText;
        }
        if (txt.value == defaultText && evt.type == "focus") {
            txt.style.color = "black";
            txt.value = "";
        }
    }
</script>
 
Server Side
Inside the Page Load event handler, two JavaScript event handlers i.e. onblur and onfocus have been added as Attribute.
Note: Both onblur and onfocus event handler triggers WaterMark JavaScript function.
 
C#
protected void Page_Load(object sender, EventArgs e)
{
    txtName.Attributes.Add("onblur", "WaterMark(this, event);");
    txtName.Attributes.Add("onfocus", "WaterMark(this, event);");
}
 
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    txtName.Attributes.Add("onblur", "WaterMark(this, event);")
    txtName.Attributes.Add("onfocus", "WaterMark(this, event);")
End Sub
 
 
Screenshot
Watermark TextBox using JavaScript
 
 
Demo
 
 
Downloads