Created
March 27, 2014 18:41
-
-
Save sdthornton/9814976 to your computer and use it in GitHub Desktop.
Robust Placeholder Support
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
// 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