Created
January 25, 2013 18:28
-
-
Save timkindberg/4636712 to your computer and use it in GitHub Desktop.
JQuery polyfill for input placeholders.
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($){ | |
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