Created
December 12, 2011 18:43
-
-
Save jk3us/1468520 to your computer and use it in GitHub Desktop.
jquery placeholder plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
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
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.