Created
March 10, 2011 09:17
-
-
Save xbb/863803 to your computer and use it in GitHub Desktop.
adds placeholder support to browsers not supporting HTML5 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
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