Skip to content

Instantly share code, notes, and snippets.

@xbb
Created March 10, 2011 09:17
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 xbb/863803 to your computer and use it in GitHub Desktop.
Save xbb/863803 to your computer and use it in GitHub Desktop.
adds placeholder support to browsers not supporting HTML5 placeholders
if ( ! Modernizr.input.placeholder) {
var phId = 0;
$('[placeholder]').each(function(){
var $input = $(this),
label = document.createElement('label');
this.id = this.id || 'input-placeholder-' + (++phId);
label.innerHTML = $input.attr('placeholder');
label.htmlFor = this.id;
$input.after(label);
label.style.position = 'absolute';
label.className = 'placeholder';
var inputHeight = $input.outerHeight(true),
labelHeight = $(label).outerHeight(true),
paddingLeft = parseInt($input.css('padding-left')) + (parseInt($input.css('margin-left')) || 0) + parseInt($input.css('border-left-width'));
label.style.top = $input.position().top + Math.floor((inputHeight / 2) - (labelHeight / 2)) + 'px';
label.style.left = $input.position().left + paddingLeft + 'px';
var hasText = function() {
return $input.val() != '';
};
var showPlaceholder = function() { label.style.display = 'block'; },
hidePlaceholder = function() { label.style.display = 'none'; };
$input.bind('focus blur', function(event){
if ( ! hasText()) {
if (event.type === 'focus') hidePlaceholder();
else showPlaceholder();
}
});
if ( ! hasText()) showPlaceholder();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment