Skip to content

Instantly share code, notes, and snippets.

@jonkemp
Last active December 15, 2015 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonkemp/5337793 to your computer and use it in GitHub Desktop.
Save jonkemp/5337793 to your computer and use it in GitHub Desktop.
Placeholder polyfill for inputs. Detects support for the placeholder attribute on inputs. If it is not present, the placeholder attribute text is inserted into the input, and a class of "placeholder-text" is added to the input. On keydown on the input, the placeholder text and the class is removed. On blur, if the input is empty, the placeholder…
// Jonathan's placeholder polyfill
// *Requires jQuery
(function () {
function PlaceholderDefaults() {
return {
'placeholderText': '',
'className': ''
};
}
function placeholderInit(selector, options) {
var obj = new PlaceholderDefaults();
$.extend(obj, options);
if ($(selector).val() === '') {
$(selector).val(obj.placeholderText).addClass(obj.className);
}
}
function placeholderRemove(selector, options) {
var obj = new PlaceholderDefaults();
$.extend(obj, options);
if ($(selector).val() === obj.placeholderText) {
$(selector).val('').removeClass(obj.className);
}
}
if ('placeholder' in document.createElement('input') === false) {
$('input[placeholder]').each(function () {
var options = new PlaceholderDefaults();
options.placeholderText = $(this).attr('placeholder');
options.className = 'placeholder-text';
$(this).on('focus', function () {
placeholderRemove(this, options);
});
$(this).on('blur', function () {
placeholderInit(this, options);
});
placeholderInit(this, options);
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment