Revision: 34866
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at October 29, 2010 07:21 by dre1080
Initial Code
/*
* Andrew Wayne 2010
* A fallback for html5 placeholder attribute
*/
var placeholder = {
isPassword: function(input) {
return $(input).attr('realType') === 'password';
},
valueIsPlaceholder: function (input) {
return input.value === $(input).attr('placeholder');
},
showPlaceholder: function (input, loading) {
// FF and IE save values when you refresh the page. If the user refreshes the page
// with the placeholders showing they will be the default values and the input fields won't
// be empty. Using loading && valueIsPlaceholder is a hack to get around this and highlight
// the placeholders properly on refresh.
if (input.value === '' || (loading && placeholder.valueIsPlaceholder(input))) {
if (placeholder.isPassword(input)) {
// Must use setAttribute rather than jQuery as jQuery throws an exception
// when changing type to maintain compatability with IE.
// We use our own "compatability" method by simply swallowing the error.
try {
input.setAttribute('type', 'input');
} catch (e) { }
}
input.value = $(input).attr('placeholder');
$(input).addClass('placeholder');
}
},
hidePlaceholder: function(input) {
if (placeholder.valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
if (placeholder.isPassword(input)) {
try {
input.setAttribute('type', 'password');
// Opera loses focus when you change the type, so we have to refocus it.
input.focus();
} catch (e) { }
}
input.value = '';
$(input).removeClass('placeholder');
}
},
init: function () {
$(':text[placeholder],:password[placeholder]').each(function(index) {
var $this = $(this);
// We change the type of password fields to text so their placeholder shows.
// We need to store somewhere that they are actually password fields so we can convert
// back when the users types something in.
if ($this.attr('type') === 'password') {
$this.attr('realType', 'password');
}
placeholder.showPlaceholder(this, true);
$this.focus(function() { placeholder.hidePlaceholder(this); });
$this.blur(function() { placeholder.showPlaceholder(this, false); });
});
}
};
// Example usage
Markup: <input placeholder="Enter Name" type="text"/>
JS:
// This example assumes you use Modernizr lib to check for available attributes
if (!Modernizr.input.placeholder) {
// no placeholder support :(
// fall back to a scripted solution
placeholder.init();
}
Initial URL
Initial Description
Initial Title
Fallback for Placeholder
Initial Tags
Initial Language
jQuery