Show a "ghost" example of text in the field and then clear it
I'm trying to duplicate the effect used in Firefox's search box, where if there is no focus in the search box (the user hasn't clicked inside it) it just tells Google to gray text. Then, when the user clicks on the field, the text is removed and they can complete their search query.
I want to use this to provide sample field data for a web form.
JQuery syntax is preferred over plain javascript, but plain JS is fine too.
Regards, Smile!
<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.className = 'normal';
}
}
elem.onblur = function ()
{
if (elem.value == '')
{
elem.value = hintText;
elem.className = 'ghost';
}
}
}
addTextHint(document.getElementById('foobar'),'Google');
</script>
Just hacked this for you. I'm sure jQuery will shrink, but I'm not using it.
source to share
This technique is so often used that it is now explicitly supported in the HTML spec through the placeholder attribute of the input tag: HTML placeholder attribute
It is already supported in most browsers , and for older browsers a jquery plugin provides a shim implementation that can be found here .
For styling placeholder text refer to this (live examples included):
HTML5 Layout Style with CSS
source to share
JQuery execution
<input type="text" id = "textField" value="Google" class="RegularText GhostText" />
<style>
.GhostText{color:#DDD}
.RegularText{color:#CCC}
</style>
<script type="text/javascript" language="javascript">
$("#textField").blur(function(e){
if ($.trim(e.target.value) == "") {
e.target.value = e.target.defaultValue;
e.target.toggleClass("GhostText");
}
});
$("#textField").focus(function(e){
if ($.trim(e.target.value) == e.target.defaultValue) {
e.target.value = "";
e.target.toggleClass("GhostText");
}
});
</script>
source to share