Archive for October, 2011

JQuery: Creating a Text Watermark

Update: Read about my JQuery plugin which handles inputs, textareas, and even passwords! It is super easy to implement and very lightweight.

My post on creating a text watermark with javascript has been pretty popular. One comment had to do with being able to implement that watermark without being able to edit the HTML (only having access to CSS and Javascript). The easy solution to that is using JQuery. So as a follow up to that post, I wrote a quick tutorial on a text watermark using JQuery instead of plain old Javascript. Here is an example in action:


To do this, you’ll need the following code:

The HTML:

<input id="inputTextboxId" type="text" />

The Javascript:

$(document).ready(function() {
 var watermark = 'textbox watermark text';
 $('#inputTextboxId').blur(function(){
  if ($(this).val().length == 0)
    $(this).val(watermark).addClass('watermark');
 }).focus(function(){
  if ($(this).val() == watermark)
    $(this).val('').removeClass('watermark');
 }).val(watermark).addClass('watermark');
});

This javascript binds an event to both the blur and focus events of the input field. When the field gains focus (someone clicks in), the JS checks to see if the value of the input field is equivalent to the watermark, in which case it will clear it. When the field loses focus (someone clicks out), the JS checks to see if the field is empty, and if it is, places the watermark back in. The javascript also sets the default value of the textbox to the watermark so that you don’t have to edit the HTML at all. All of the “addClass” and “removeClass” events are only necessary if you wish to style the watermark differently than regular text input. To use this, you’ll need some CSS too.

Lastly, the CSS if you are feeling fancy:

input.watermark { color: #999; }

That’s it! A simple text watermark using JQuery that doesn’t require touching HTML at all.