Input Placeholder Text with Progressive Enhancement
used HTML5 placeholder attribute on supported browsers, javascript fallback on non-supported (IE).
source:
http://robertnyman.com/2010/06/17/adding-html5-placeholder-attribute-support-through-progressive-enhancement/
by SebastianPataneMasuelli
May 17, 2011
HTML
<input type="text" id="search-text" placeholder="Enter terms here"><br /><br />
<input type="text" id="input1" placeholder="Enter terms here 1"><br /><br />
<input type="text" id="input2" placeholder="Enter terms here 2"><br /><br />
<input type="text" id="input3" placeholder="Enter terms here 3"><br /><br />
<input type="text" id="input4" placeholder="Enter terms here 4"><br /><br />
CSS
.placeholder {
color: #aaa;
}
JavaScript
// To detect native support for the HTML5 placeholder attribute
var searchField, originalText, fakeInput = document.createElement("input"),
placeHolderSupport = ("placeholder" in fakeInput),
clearValue = function(searchField, originalText) {
if (searchField.val() === originalText) {
searchField.val("");
}
};
// Applies placeholder attribute behavior in web browsers that don't support it (IE)
if (!placeHolderSupport) {
//loop through inputs with the placeholder attribute
$('input[placeholder]').each(function() {
searchField = $(this);
originalText = searchField.attr("placeholder");
searchField.val(originalText);
searchField.addClass("placeholder");
});
//bind focus actions and values;
$('input[placeholder]').bind("focus", function() {
searchField = $(this);
originalText = searchField.attr("placeholder");
//alert('focus: ' + searchField.attr('class'));
searchField.removeClass("placeholder");
//alert('focus: ' + searchField.attr('class'));
clearValue(searchField, originalText);
});
//bind blur actions and values;
$('input[placeholder]').bind("blur", function() {
searchField = $(this);
originalText = searchField.attr("placeholder");
if (searchField.val().length === 0) {
searchField.val(originalText);
searchField.addClass("placeholder");
}
});
// Empties the placeholder text at form submit if it hasn't changed
$('input[placeholder]').parents("form").bind("submit", function() {
$('input[placeholder]').each(function() {
searchField = $(this);
originalText = searchField.attr("placeholder");
clearValue(searchField, originalText);
});
});
// Clear at window reload to avoid it stored in autocomplete
$(window).bind("unload", function() {
$('input[placeholder]').each(function()...