Skip to content

Instantly share code, notes, and snippets.

@sdthornton
Created March 27, 2014 18:41
Show Gist options
  • Save sdthornton/9814976 to your computer and use it in GitHub Desktop.
Save sdthornton/9814976 to your computer and use it in GitHub Desktop.
Robust Placeholder Support
// Use more robust placeholder support when specified
// Because it wraps with a div, it can potentially break an inputs position,
// so secondary placeholder support is provided as alternative
$('.placeholder_support').each(function(i, el) {
var $input = $(el),
holderId = $input.attr('id') + "_placeholder",
placeholder = $input.attr('placeholder'),
lineHeight = $input.css('line-height'),
paddingTop = parseInt($input.css('padding-top'), 10)
+ parseInt($input.css('border-top-width'), 10) + 'px',
left = $input.css('padding-left'),
fontSize = $input.css('font-size');
$input.wrap('<div style="position:relative;"></div>');
var placeholderHTML = $('<span />', {
'id': holderId,
'class': 'placeholder_span placeholder',
'text': placeholder
}).css({
position: 'absolute',
top: '0',
left: left,
lineHeight: lineHeight,
paddingTop: paddingTop,
fontSize: fontSize
}).on('click.focusInput', function(e) {
e.preventDefault();
$input.focus();
});
$input.after(placeholderHTML).on('keyup.hidePlaceholder', function() {
if ($(this).val() == '') {
placeholderHTML.show();
} else {
placeholderHTML.hide();
}
}).on('blur.showPlaceholder', function() {
if ($(this).val() == '') {
placeholderHTML.show();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment