jQuery string limit display on key press

Toggle class name on click in jQuery

by lemon kazi

HTML

<input type="text" name="noteTitle" id="noteTitle" maxlength="100"   onkeyup="checkLength(this,'titleLength')" />
<div id="titleLength">100</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

//take field (fieldToCheckMax), and its counterID(titleLength)
function checkLength(fieldToCheckMax,counterID){

	//get the maxallowed for the input
	maxAllowed=fieldToCheckMax.getAttribute('maxlength');
	//save the affected counter in a variable
	counterID=document.getElementById(counterID);
	//change the value based on the max allowed, to switch between green and red
	counterID.innerHTML=colorChanger();
	//the color based checker, to decide is it red or green
	function colorChanger(){
			if(fieldToCheckMax.value.length < maxAllowed) {
				counterID.style.color='green';
				return maxAllowed-fieldToCheckMax.value.length+ ' of 200';
			}
			else {
				counterID.style.color='red';
				return maxAllowed-fieldToCheckMax.value.length + ' of 200';
			}

	}
}