jQuery clear focus function

I had a problem on a site whereby the forms were designed so that the labels were essentially inside the text inputs. I found this looked nicer as it was less all over the place and the information of what needed to be entered in the field (e.g. email address) was easy to make out. I made the form so that when you clicked in the field, it cleared out the input. The problem here is that you now don’t know what needs to go in there. You may have lost concentration for a second and come back to the room adn thought @Was that email address or first name that needed to be entered here?’

I came up with a solution to the problem so that when you click off the input, if you have not entered any information, it puts the label back in. Its quite simple, but a nice little touch for usability. Here is how to do it using  jQuery…

Theres the standard jQuery file to include and a couple of functions I wrote using jQuery. One for the focus event (when you click in the input) and one for the blur event (when you click away from the input). Basically it uses a title on the input that is the same as the value to begin with. This is saved in a variable and once the input is focussed on and then the input is cleared so you can type away.
When you move away from the input, if nothing has been entered, it will replace it with the original value that was saved in the variable from the title. kind of like I have noticed a lot of forms on Facebook have started doing to clear and replenish unentered fields.

Below is the javascript code I use when doing this:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){

var clearMePrevious = '';

// clear input on focus
$('.clearMeFocus').focus(function()
{
if($(this).val()==$(this).attr('title'))
{
clearMePrevious = $(this).val();
$(this).val('');
}
});

// if field is empty afterward, add text again
$('.clearMeFocus').blur(function()
{
if($(this).val()=='')
{
$(this).val(clearMePrevious);
}
});
});

</script>

And here is the way I code the text inputs.

<input type="text" name="email" title="Enter your email" value="Enter your email" class="clearMeFocus" />

The class ‘clearMeFocus’ is used so you know which fields on a form want to use this feature and also to grab the title and value from it. (I guess you don’t have to use that to get the info though…)

I have also put up an example of the jQuery functions and the form in action. It’s a simple form, but you get the idea…it can be found here.