Skip to content

Instantly share code, notes, and snippets.

@epoberezkin
Created March 16, 2013 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epoberezkin/5176003 to your computer and use it in GitHub Desktop.
Save epoberezkin/5176003 to your computer and use it in GitHub Desktop.
Placeholders for IE without touching the field content
// Enables placeholders if they are not natively supported
// uses jQoery
// usage:
// placeholder('input[type="text"]', 'form#my_form');
function placeholder (inputsOrSelector, context) {
var attributesToCopy = [
'font-size',
'font-weight'
];
// Return if native support is available.
if ('placeholder' in document.createElement('input')) return;
var inputs = inputsOrSelector.jquery
? inputsOrSelector
: (context
? $(inputsOrSelector, context.jquery
? context
: $(context))
: $(inputsOrSelector));
inputs.each(function() {
var input = $(this);
// create placeholder
var placeholderText = input.attr('placeholder');
if (! placeholderText) return;
// check that placeholder isn't already there
if (input.next().is('span.placeholder')) {
input.trigger('change');
return;
}
var placeholder = $('<span class="placeholder">' + placeholderText + '</span>');
placeholder.css(input.css(attributesToCopy));
placeholder.css({
// to make placeholder centered vertically
'line-height': input.outerHeight() + 'px',
'margin-left': input.css('padding-left')
})
// insert placeholder in the same parent where input element is
var parent = input.parent();
var parentPosition = parent.css('position');
// make parent realative if it is not
if (parentPosition !== 'absolute' && parentPosition !== 'relative')
parent.css('position', 'relative');
input.after(placeholder);
// position placeholder correctly
placeholder.css({
position: 'absolute',
top: input.position().top + 'px',
left: input.position().left + 'px'
});
// show/hide placeholder depending on field
input.on('change keyup', function() {
placeholder[input.val() ? 'hide' : 'show']();
});
input.trigger('change');
// put cursor in field
placeholder.on('click', function() {
input.focus();
});
});
}
All placeholders plugins I could find were inserting placeholder in the field itself.
This approach has many disadvantages.
1. If your JavaScript code throws an exception you are stuck with the wrong field content that can be submitted.
2. Few of these plugins work for password fields, and those that do are quite complex.
3. You can't style placeholder created this way differently from the field content.
So I created placeholders that are additional elements that places themselves on top of the fields and show/hide depending on whether the filed is empty.
Placeholder element created with this function is span.placeholder, it should be added to the list of CSS rules used to style placeholders.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment