views:

1875

answers:

3

I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says Google in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.

I want to use this to provide example field data for a web form.

JQuery syntax would be preferable to plain javascript, but plain JS would be fine too.

Thanks SO Hive Mind!

A: 
  $(selector).text('Google'); 
  $(selector).click(function(){
    $(this).text('');
  });

There's probably a more elegant way to do it, but this assumes your box has no text in it at page load. If it does you can remove the first line.

I haven't tested this, but it should work.

Leanan
Things wrong with this: 1. Doesn't reclear if you leave it blank. 2. Doesnt support tabs 3. Doesn't ghost text 4. Clears user text if refocused.
FlySwat
+5  A: 
<style type='text/css'>
      input #ghost { color: #CCC; }
      input #normal { color: #OOO; }
</style>

<script type='text/javascript'> 
    function addTextHint(elem, hintText)
    {  
     if (elem.value == '') 
     {  
      elem.value = hintText;
      elem.style.className = 'ghost';
     }

     elem.onfocus = function ()
     {   
      if (elem.value == hintText)   
      {
       elem.value = '';
       elem.style.className = 'normal';
      }
     }

     elem.onblur = function ()
     {
      if (elem.value == '')
      {
       elem.value = hintText;
       elem.style.className = 'ghost';
      }
     }   
    }

    addTextHint(document.getElementById('foobar'),'Google');
</script>

Just whipped this up for you. jQuery would make it smaller I'm sure, but I don't use it.

FlySwat
only I'd replace color switching with css class switching.
Kon
Good call, Edited.
FlySwat
There are a few gotchas with this. If you submit this form without changing the values then "Google" will be sent as your text. This may not be what you want. Even if you filter the value server side, the client's browser will store the value and use it as the default value on future page views.
Josh
+2  A: 

Another way is to use some CSS, create an image with the background text you want, and set that as the background image of the text box, then when the text box get's focus you could switch styles to remove that background image.

Nick