textbox watermark text effect

What is it

click on the textboxes below:



Add watermark text effect to your textbox and textarea controls. Texboxes will show default text to begin with. When the textbox gains focus, the default text goes off, user types in his own text and that persists. If user doesn’t type in anything and moves on to other parts of your web page, your textbox again show the default text.

How to achieve that

I’ve written this small javascript which renders the said effect to textboxes and textareas. To set things up all you need to do is:

  1. give the textboxes/textareas an additional class of ‘js_watermark’. eg:
  2. Add the following javascript somewhere
    $(document).ready(function(){
    /*---watermark functions ------------*/
    		$(".js_watermark").each(function(){
    			$(this).after("");
    		});
    		$(".js_watermark").focus(function(){
    			var wm_text = $(this).next('.js_watermar_text').html();
    
    			if($(this).val()==wm_text){$(this).val('');}
    		});
    		$(".js_watermark").blur(function(){
    			var wm_text = $(this).next('.js_watermar_text').html();
    			if($.trim($(this).val())==""){$(this).val(wm_text);}
    		});
    		/*--------------------------------------*/
    });

The approach is simple:
once the html is loaded the javscript adds a hidden <span> tag next to each textboxes/textareas which have the class js_watermark and ‘stores’ the default values of textboxes in those spans. When you click on any textbox (gain focus event) its text is deleted. When textbox loses focus the script check if its text is blank (after trimming blank spaces), if yes it fetches the default value from the hidden span next to the textbox and sets the textboxes value with the default value again.

Hope you find it useful.

Published by

Chandan Chaudhary

Chandan is a WordPress guy. A programmer at heart. He loves building community sites with WordPress and BuddyPress.

Leave a Reply

Your email address will not be published. Required fields are marked *