Skip to content

Instantly share code, notes, and snippets.

@sillero
Created August 21, 2012 17:02
Show Gist options
  • Save sillero/3417312 to your computer and use it in GitHub Desktop.
Save sillero/3417312 to your computer and use it in GitHub Desktop.
Placeholder polyfill (jQuery)
function placeholderPolyfill(el, opt){
opt = opt || {};
var $el = $(el),
testAttribute = function(element, attribute) {
var test = document.createElement(element);
return (attribute in test);
};
if (!testAttribute('input','placeholder') && $el.attr('placeholder').length) {
var defaults = {
clearOnSubmit: true
};
opt = $.extend({}, defaults, opt);
var placeholder = $el.attr('placeholder');
if (!$el.val().length)
$el.val(placeholder);
$el.focus(function(){
if ($(this).val() == placeholder)
$(this).val('');
}).blur(function(){
if (!$(this).val().length)
$(this).val(placeholder);
});
if (opt.clearOnSubmit) {
$el.closest('form').bind('submit.placeholder', function(){
if ($el.val() == placeholder)
$el.val('');
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment