Introduction
This is a really easy snippet to implement, it's going to feel like a freebie. We need only two reusable JavaScript functions. The first handles when a user focuses on the field, and the second handles when a user removes that focus.
Here are the two functions in full.
JavaScript Functions
function handleFocus(element)
{
if (element.value == element.defaultValue)
{
element.value = '';
}
}
function handleBlur(element)
{
if (element.value == '')
{
element.value = element.defaultValue;
}
}
Here they are in plain english.
handleFocus: If the newly focused element contains the suggestion text, empty the field.
handleBlur: If the element which just lost focus is now empty, replace with the suggestion text.
Creating our Input Fields
Finally, we need to set up each input field with proper 'onfocus' and 'onblur' event handling. Make sure to add your suggestion text in the 'value' attribute!
Live Demo
Conclusion
While there isn't much to implementing this snippet, the functionality it adds is sure to turn heads. Usability is the name of the game, and this is a great step towards making that a reality for your users.
Please post any comments/suggestions below. Feedback is always appreciated, it lets us know how we are doing and how we can better serve the community!
