HTML
<form class="infield-labels">
<label for="name">Your Name</label>
<input type="text" name="name" />
<label for="email">Your Mail</label>
<input type="text" name="email" />
<input type="submit" value="send" />
</form>
jQuery
$(document).ready(function(){
/*
I'm sorry I missed putting some toggleClass functionality
to the script. Either way didn't work as expected so you
sadly have to add color definitions to the functions call.
*/
inFieldLabels('#000', '#bbb');
});
function inFieldLabels(darkColor, lightColor)
{
// do something with each matching input
$('.infield-labels').find('input').each(function(){
// get name of input for later reference
var input_name = $(this).attr('name');
// do something with each matching label
$(this).parent().find('label').each(function(){
// but only for the one matching the input-name
if ($(this).attr('for') == input_name){
// set counter to zero (for later use)
var c = 0;
// get inner HTML (text) of label tag
var label = $(this).text();
// get "label-referenced" (for="foobar") input
var input = $(this).parent().find('input[name='+input_name+']');
// apply label-text as input value
input.val(label);
// remove label element from dom
$(this).remove();
// listen for focus
input.bind('focus', function(){
// listen for keyboard input; but only once (use counter here)
$(this).bind('keypress', function(){
c++;
if (c == 1
&& $(this).val() == label){
// if user starts typing color is set to dark and placeholder removed
$(this).css({ "color": darkColor });
$(this).val('');
}
});
if ($(this).val() == label){
// if there is a focus on default label use light color
$(this).css({ "color": lightColor });
} else {
// oposite
$(this).css({ "color": darkColor });
}
// listen for blur
}).bind('blur', function(){
// set counter to zero again
c = 0;
if ($(this).val().length == 0){
// if input was left empty but back default value
$(this).val(label);
}
// and finaly use dark color again
$(this).css({ "color": darkColor });
});
}
});
})
}