Skip to content

Instantly share code, notes, and snippets.

@jasonkeene
Last active October 5, 2015 07:08
Show Gist options
  • Save jasonkeene/2769208 to your computer and use it in GitHub Desktop.
Save jasonkeene/2769208 to your computer and use it in GitHub Desktop.
Placeholder Text Shim
// placeholder text fallback
// requires modernizer and jQuery
$(function () {
if (!Modernizr.input.placeholder) {
var placeholder_text_color = '#999999';
function hide_placeholder_fake(real, fake) {
real.show();
real.focus();
fake.hide();
}
function show_placeholder_fake(real, fake) {
if (!real.val()) {
fake.show();
real.hide();
}
}
function create_placeholder_fake(real) {
var fake = $('<input type="text" />'), // create a fake element
i = 0,
attrs = real.get(0).attributes,
attr;
fake.attr('id', real.attr('id') + '_fake');
fake.val(real.attr('placeholder'));
fake.css('color', placeholder_text_color);
fake.hide();
// copy over all the attrs from real element
for (i = 0; i < attrs.length; i++) {
attr = attrs[i];
if (attr.name !== 'type' &&
attr.name !== 'id' &&
attr.name !== 'name' &&
attr.name !== 'placeholder' ) {
fake.attr(attr.name, attr.value);
}
}
real.after(fake);
return fake;
}
$('input[placeholder]').each(function () {
var real = $(this), // bind element to the current scope
fake = create_placeholder_fake(real);
// if the input isn't currently focused then show placeholder fake
if (!real.is(document.activeElement)) {
show_placeholder_fake(real, fake);
}
fake.focus(function () { hide_placeholder_fake(real, fake); });
real.blur(function () { show_placeholder_fake(real, fake); });
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment