Skip to content

Instantly share code, notes, and snippets.

@catchamonkey
Created April 5, 2013 14:22
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 catchamonkey/5319645 to your computer and use it in GitHub Desktop.
Save catchamonkey/5319645 to your computer and use it in GitHub Desktop.
JavaScript placeholder polyfill.
function isPlaceholderSupported() {
var input = document.createElement("input");
return ('placeholder' in input);
}
var placeholdersupport = isPlaceholderSupported();
// find the elements that are advertising this behaviour
// then setup each one
$("[data-behaviour='placeholder']").each(function() {
var placeholderText, elements, inputValue;
element = $(this);
placeholderText = element.attr('placeholder');
inputValue = element.attr('value');
// use the input value if present instead of the placeholder
if (inputValue != '') {
placeholderText = inputValue;
};
// polyfill
if (!placeholdersupport) {
element.val(placeholderText);
element.focus(function() {
if ($(this).val() == placeholderText) {
$(this).val('');
}
});
element.blur(function() {
if($(this).val() == '') {
$(this).val(placeholderText);
}
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment