public
Last active

shim for browsers that don't support the html5 placeholder attribute

  • Download Gist
placeholder.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 
 
setup_placeholders = (function() {
$.support.placeholder = false;
test = document.createElement('input');
if('placeholder' in test) {
$.support.placeholder = true;
return function() {}
} else {
return function(){
$(function() {
var active = document.activeElement;
$('form').delegate(':text', 'focus', function () {
var _placeholder = $(this).attr('placeholder'),
_val = $(this).val();
if (_placeholder != '' && _val == _placeholder) {
$(this).val('').removeClass('hasPlaceholder');
}
}).delegate(':text', 'blur', function () {
var _placeholder = $(this).attr('placeholder'),
_val = $(this).val();
// No need to test for values specific to a particular jQuery version
// undefined and an empty string both are falsy
if (!_placeholder && ( _val == '' || _val == _placeholder)) {
$(this).val(_placeholder).addClass('hasPlaceholder');
}
}).submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
$(':text').blur();
$(active).focus();
});
}
}
})();

.attr('blah') returns undefined in newer versions of jQuery - you can work around this using:

var _placeholder = $(this).attr('placeholder') || ''

https://gist.github.com/3084976

Updated to be friendly to more versions of jQuery. May update for prop method detection too.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.