To address the problem of the placeholders not showing up initially, you need to initialize each of them when the page loads, something like this:
$('[placeholder]').each(function(){
var $this = $(this);
if($this.val() == ''){
$this.val($this.data('placeholder')).addClass('placeholder');
}
});
The problem with the text color is that the .placeholder
class is being added/removed on focus or blur, not when the user types. You need an additional event handler for keyup that removes the .placeholder
class (this also includes my snippet from above):
var isInputSupported = 'placeholder' in document.createElement('input');
var isTextareaSupported = 'placeholder' in document.createElement('textarea');
if (!isInputSupported || !isTextareaSupported) {
$('[placeholder]').each(function(){
var $this = $(this);
if($this.val() == ''){
$this.val($this.data('placeholder')).addClass('placeholder');
}
});
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).on('keyup', function(){
$(this).removeClass('placeholder')
}).blur(function () {
var input = $(this);
if (input.val() == '') {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
input.data('placeholder', true);
} else {
input.data('placeholder', false);
}
}).blur().parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
}
})
});
}