Skip to content

Instantly share code, notes, and snippets.

@jk3us
Created December 12, 2011 18:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jk3us/1468520 to your computer and use it in GitHub Desktop.
Save jk3us/1468520 to your computer and use it in GitHub Desktop.
jquery placeholder plugin
(function($) { jQuery.fn.placeholder = function() {
var i = document.createElement('input'); if ('placeholder' in i) return;
$(this).filter('textarea').each(function(){
var placeholder = $(this).attr('placeholder');
$(this).html(placeholder);
$(this).css({color:'#999999'});
$(this).bind('focus', function(){
if($(this).html()==placeholder) {
$(this).html('');
$(this).css({color:'#000'});
}
})
$(this).bind('blur', function(){
if(!$(this).html()) {
$(this).html(placeholder);
$(this).css({color:'#999999'});
}
})
});
var counter=0;
$(this).filter('input').each(function(){
var input=this,
placeholder=$(this).attr('placeholder');
if ($(this).attr('type')=='password') {
var thisdummy = 'dummy' + counter;
$(this)
.hide()
.before('<input type="text" id="' + thisdummy + '"/>')
$('#' + thisdummy)
.val(placeholder)
.css({color:'#999999'})
if ($(this).attr('tabindex')) {
$('#' + thisdummy).attr('tabindex',$(this).attr('tabindex'));
}
counter++;
$('#' + thisdummy).bind('focus', function(){
$(input)
.show()
.val('')
.focus()
$(this).hide();
})
$(this).bind('blur', function(){
if (!$(this).val()) {
$(this).hide();
$('#' + thisdummy).show();
}
})
} else {
$(this)
.val(placeholder)
.css({color:'#999999'})
$(this).bind('focus', function(){
if ($(this).val()==placeholder) {
$(this)
.val('')
.css({color:'#000'})
}
})
$(this).bind('blur', function(){
if (!$(this).val()) {
$(this)
.val(placeholder)
.css({color:'#999999'})
}
})
}
})
}})(jQuery);
@jk3us
Copy link
Author

jk3us commented Dec 12, 2011

This is based on the goodplaceholder plugin found at http://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there (tibalt's version on 7/17/2012), I've made a few changes and posted it here, enjoy.

@jk3us
Copy link
Author

jk3us commented May 29, 2012

Updated to handle tabindex better for password fields... by duplicating the same tabindex on the dummy and putting the dummy before the original field (instead of after it).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment