JQuery Textbox Hint

In most of the websites, you might notice textboxes with gray text inside which explains what is it for, and when you focus on the textbox it disappears and reappears when you leave the empty textbox.

To achieve this, what i do is:
– get the hint text from title attribute of textbox.
– Show hint text when textbox is empty and not in focus.
– Hide hint text when input box has the focus and title attribute matches input text.

See live Demo here and view the source if you’d like.

Let us take a sample HTML

<div id="block">
   <input type="text" value="" title="search entire site" /> <br/><br/>
   <input type="text" value="" title="Enter email address" /> <br/> <br/>
   <input type="text" value="" title="Enter user name" /> 

Call the textbox hint function

    function() {

Here is the textboxHint function, it will take the input boxes container id and you can pass options like input box selector within a container and blur class. options parameter is optional, default selector is input:text[title] means input boxes which has title attributes and blur class is “blur“.

 function textboxHint(id, options) {
    var o = { selector: 'input:text[title]', blurClass:'blur' };
    $e = $('#'+id);
    $.extend(true, o, options || {});
    if ($e.is(':text')) {
      if (!$e.attr('title')) $e = null;
    } else {
      $e = $e.find(o.selector);
    if ($e) {
      $e.each(function() {
      var $t = $(this);
      if ($.trim($t.val()).length == 0) { $t.val($t.attr('title')); }
      if ($t.val() == $t.attr('title')) {
      } else {

     $t.focus(function() {
	if ($.trim($t.val()) == $t.attr('title')) {
	}).blur(function() {
	  var val = $.trim($t.val());
	  if (val.length == 0 || val == $t.attr('title')) {
         // empty the text box on form submit				
	  if ($.trim($t.val()) == $t.attr('title')) $t.val('');

Here is the blur css that you can add in the head tag.

input.blur {

Add a Comment

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