Skip to content

Instantly share code, notes, and snippets.

@timkindberg
Created January 25, 2013 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timkindberg/4636712 to your computer and use it in GitHub Desktop.
Save timkindberg/4636712 to your computer and use it in GitHub Desktop.
JQuery polyfill for input placeholders.
;(function($){
var alreadySupported = 'placeholder' in document.createElement('input');
function doPlaceholder(){
if(alreadySupported) return;
var $this = $(this);
if($this.data('placeholder-polyfill'))return;
$this.data('placeholder-polyfill', true);
if(!$this.is('[type="text"], [type="password"], [type="email"], textarea')) return;
$this.wrap('<span style="position:relative" />');
var $id = $this.attr('id');
if(!$id) $this.attr('id', $id = 'placeholder-' + (0|Math.random()*1000000).toString(36));
var l = $('<label class="placeholder" for='+$id+'/>')
.css({
position: 'absolute',
cursor: 'text'
})
.text($this.attr('placeholder'))
.insertBefore($this);
$this.removeAttr('placeholder');
function update(){
if($this.val() == ''){
l.show();
}else{
l.hide();
}
}
$this.bind('change keyup', update);
$this.bind('keydown', function(){
l.hide();
});
$this.focus(function(){
l.addClass('focused');
});
$this.blur(function(){
l.removeClass('focused');
});
update();
// Password managers can be varying degrees of slow.
setTimeout(update, 100);
setTimeout(update, 500);
setTimeout(update, 1000);
}
$.fn.placeholder = function(){
return this.each(doPlaceholder);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment