jQuery Input Text Replacement

Edit (July 1, 2011): This snippet has been dated for years.

A Modern Approach

If you need something quick that targets modern browsers you might want to consider using the HTML5 placeholder attribute instead of a javascript solution. Cross-browser support isn’t the best (it doesn’t look like IE9 supports it at all, but if the placeholder text isn’t critical to the functionality it might be the right solution.

<input type="text" name="search" placeholder="Search"  />

Further reading on the placeholder attribute.

If that won’t do it, check out this Cross-Browser HTML5 Placeholder Text on Web Designer Wall if you’re looking for something more modern.

Finally, you can do it with jQuery (or plain ol’ Javascript) as my original post from 2008 demonstrates…

Thought I’d save this handy dandy function for later.
Makes the text in an input disappear when you click on the input.

The Function

function textReplacement(input){
   var originalvalue = input.val();
   input.focus( function(){
      if( $.trim(input.val()) === originalvalue ){ input.val(""); }
   });
   input.blur( function(){
      if( $.trim(input.val()) === "" ){ input.val(originalvalue); }
   });
}

Using It

textReplacement($('#inputname'));

Example

jQuery Random Colour Generator

I can’t remember the inspiration for this crazy thing, but I’m sure somewhere out there someone is looking for a random colour generator that is done in jQuery.

So if you’re feeling in the mood to have a randomly changing colour … this is the script for you! Essentially it’s just generating a random number between 0 and 255 for red, green, and blue. It then uses CSS to change the colour property of an element (that’s easily customizable by you).

So check out the demo.