JSFiddle - React, Tailwind, and code Playground
HTML
<form action="index.html" novalidate>
<input type="text" name="first-name" placeholder="Enter first name">
<input type="text" name="last-name" placeholder="Enter last name">
<input type="tel" name="phone-no" placeholder="What is your phone no?">
<input type="email" name="email-address" placeholder="Enter your e-mail address">
<input type="password" name="user-pwd" placeholder="Choose a password">
<input type="password" name="user-pwd-repeat" placeholder="Repeat password">
<input type="submit" value="Send to myself">
</form>
JavaScript
var inputs = document.querySelectorAll("input[placeholder]"),
l = inputs.length,
// Set caret at the beginning of the input
setCaret = function (evt) {
if (this.value === this.placeholderText) {
this.setSelectionRange(0, 0);
evt.preventDefault();
evt.stopPropagation();
return false;
}
},
// Clear placeholder value at user input
clearPlaceholder = function (evt) {
if (evt.keyCode !== 9) {
if (this.value === this.placeholderText) {
this.value = "";
this.className = "active";
if (this.oType === "password") {
this.type = "password";
}
}
}
},
restorePlaceHolder = function () {
if (this.value.length === 0) {
this.value = this.placeholderText;
setCaret.apply(this, arguments);
this.className = "";
if (this.type === "password") {
this.type = "text";
}
}
},
clearPlaceholderAtSubmit = function (evt) {
for (var i=0, input; i<l; i++) {
input = inputs[i];
if (input.value === input.placeholderText) {
input.value = "";
}
}
};
for (var i=0, input; i<l; i++) {
input = inputs[i];
if (input.value.length === 0) {
input.placeholderText = input.getAttribute("placeholder");
input.removeAttribute("placeholder");
input.value = input.placeholderText;
if (input.type === "password") {
input.oType = input.type;
input.type = "text";
}
}
else {
input.className = "active";
}
// Apply events for placeholder handling
input.addEventListener("focus", setCaret, false);
input.addEventListener("click", setCaret, false);
input.addEventListener("keydown", clearPlaceholder, false);
input.addEventListener("keyup", restorePlaceHolder, false);
...