Monday, March 10, 2008

JavaScript - Create your own watermark textbox

The main purpose of a watermark is to provide information to the user about the textbox without cluttering up the page. You have probably seen many examples of this in search textboxes in websites. When a watermarked textbox is empty, it displays a message to the user. Once the user types some text into the textbox, the watermarked text disappears. When the user leaves the textbox the watermarked text appears again if the content of the textbox is empty.

You can easily change your textbox to provide watermark behavior by adding onfocus and onblur event handlers. In the focus event, clear the textbox if its text matches the watermark text. In the blur event, set the text back to watermark text if the textbox empty.
JavaScript:
function WatermarkFocus(txtElem, strWatermark)
{
if (txtElem.value == strWatermark) txtElem.value = '';
}


function WatermarkBlur(txtElem, strWatermark)
{
if (txtElem.value == '') txtElem.value = strWatermark;
}
ASPX:
<asp:TextBox ID="txtWatermark" runat="server" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
string strWatermark = "Search Karamasoft.com";
txtWatermark.Text = strWatermark;
txtWatermark.Attributes.Add("onfocus", "WatermarkFocus(this, '" +
strWatermark + "');");
txtWatermark.Attributes.Add("onblur", "WatermarkBlur(this, '" +
strWatermark + "');");
}

No comments: