Input box colour changes with text length
by Greg Bowler
HTML
<p>The text box goes through red/yellow/green depending on how many characters there are.
<input id="textbox" value="Your message here"/>
CSS
.red {
background: #f00;
}
.yellow {
background: #ff0;
}
.green {
background: #0f0;
}
.lightgreen {
background: #8f8;
}
input {
padding: 8px;
font-size: 24px;
border: 1px solid #aaa;
-webkit-transition: background 1s ease-in-out;
-ms-transition: background 1s ease-in-out;
transition: background 1s ease-in-out;
}
JavaScript
var colours = {
"red": {
"max": 3
},
"yellow": {
"max": 8
},
"green": {
"max": 15
},
},
textbox = document.getElementById("textbox"),
e_keyup = function(e) {
var i;
for(i in colours) {
this.className = "";
if(this.value.length <= colours[i].max) {
this.classList.add(i);
return;
}
}
this.classList.add("lightgreen");
};
textbox.addEventListener("keyup", e_keyup);
e_keyup.call(textbox);