/**
* This is an implementation of HTML5 placeholder=""
*
* Suggested styling: input[data-placeholder-on], textarea[data-placeholder-on] { color:GrayText }
*/
if (!HTMLInputElement.prototype.__lookupGetter__("placeholder") ||
!HTMLTextAreaElement.prototype.__lookupGetter__("placeholder")) {
HTMLInputElement.prototype.__defineGetter__("placeholder", function() {
return this.getAttribute("placeholder");
});
HTMLInputElement.prototype.__defineSetter__("placeholder", function(value) {
this.setAttribute("placeholder", value);
});
HTMLTextAreaElement.prototype.__defineGetter__("placeholder", function() {
return this.getAttribute("placeholder");
});
HTMLTextAreaElement.prototype.__defineSetter__("placeholder", function(value) {
this.setAttribute("placeholder", value);
});
function isTextField(elm) {
if (elm instanceof HTMLTextAreaElement)
return true;
if (!(elm instanceof HTMLInputElement))
return false;
return (elm.type != "checkbox" &&
elm.type != "radio" &&
elm.type != "button" &&
elm.type != "submit" &&
elm.type != "reset" &&
elm.type != "file" &&
elm.type != "hidden" &&
elm.type != "image" &&
elm.type != "datetime" &&
elm.type != "datetime-local" &&
elm.type != "date" &&
elm.type != "month" &&
elm.type != "week" &&
elm.type != "time" &&
elm.type != "range" &&
elm.type != "color");
}
function addPlaceholder(elm) {
elm.setAttribute("data-placeholder-on", elm.type);
if (elm.type == "password")
elm.type = "text";
elm.value = "\uFEFF" + elm.placeholder.replace(/\r|\n/g, "");
}
function removePlaceholder(elm) {
if (elm.getAttribute("data-placeholder-on") == "password")
elm.type = "password";
elm.value = "";
elm.removeAttribute("data-placeholder-on");
}
// add placeholders on load
window.addEventListener("DOMContentLoaded", function() {
var elms = document.querySelectorAll("input[placeholder], textarea[placeholder]");
for (var i = 0; i < elms.length; ++i) {
var elm = elms[i];
if (!isTextField(elm))
continue;
if (elm.value == "" && document.activeElement != elm) {
addPlaceholder(elm);
}
}
}, false);
// remove placeholder when focused
document.addEventListener("focus", function(e) {
if (!isTextField(e.target))
return;
if (e.target.hasAttribute("data-placeholder-on")) {
removePlaceholder(e.target);
}
}, true);
// add placeholder when blurred
document.addEventListener("blur", function(e) {
if (!isTextField(e.target) || !e.target.hasAttribute("placeholder")) {
return;
}
if (e.target.value == "") {
addPlaceholder(e.target);
}
}, true);
// remove placeholder value when submitting form
document.addEventListener("submit", function(e) {
var elms = e.target.elements;
for (var i = 0; i < elms.length; ++i) {
var elm = elms[i];
if (isTextField(elm) && elm.hasAttribute("data-placeholder-on")) {
removePlaceholder(elm);
}
}
}, true);
}