Char Counter
Char counter without libraries
by Porfirio Chavez
HTML
<form>
<textarea name="texto"></textarea>
<input type='text' readonly name="caracteres">
</form>
JavaScript
const MAX_CHARS = 10;
const textElement = document.forms[0].texto;
const charsElement = document.forms[0].caracteres;
function isValidLength(value){
return value < MAX_CHARS;
}
function setColor(element, isValid){
element.style.color = isValid ? "#000000" : "#ff0000";
}
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function (){
textElement.addEventListener('input', function(){
const elementLength = textElement.value.length;
const isValid = isValidLength(elementLength);
setColor(charsElement, isValid)
charsElement.value = elementLength;
})
})