I'm currently working on developing a function to calculate the number of characters remaining. My aim is to utilize addEventListener
to monitor event types:
var output = document.getElementById('output');
var tweetTxt = document.getElementById("tweettext");
var charCount = 10;
var tweetTxt = document.getElementById("tweettext");
function textCounter(){
console.log("it works");
var count = charCount - document.getElementById("tweettext").value.length;
if(count < 0){
output.classList.add("red");
output.classList.remove("black");
console.log("Less than zero");
}else{
output.classList.add("black");
output.classList.remove("red");
}
output.innerHTML = count + " characters left";
}
tweetTxt.addEventListener('onKeyDown', textCounter, false);
tweetTxt.addEventListener('onKeyUp', textCounter, false);
tweetTxt.addEventListener('onChange', textCounter, false);
<div class="container">
<div class="row">
<div>
<textarea name="tweettext" id="tweettext">
</textarea>
</div>
<div id="output" class="black">
</div>
</div>
</div>
For some reason, this approach isn't producing the desired outcome. However, when I attach listeners directly to the <textarea>
element, it functions properly:
var output = document.getElementById('output');
//var tweetTxt = document.getElementById("tweettext");
var charCount = 10;
var tweetTxt = document.getElementById("tweettext");
function textCounter(){
console.log("it works");
var count = charCount - document.getElementById("tweettext").value.length;
if(count < 0){
output.classList.add("red");
output.classList.remove("black");
console.log("Less than zero");
}else{
output.classList.add("black");
output.classList.remove("red");
}
output.innerHTML = count + " characters left";
}
/* tweetTxt.addEventListener('onKeyDown', textCounter, false);
tweetTxt.addEventListener('onKeyUp', textCounter, false);
tweetTxt.addEventListener('onChange', textCounter, false); */
<div class="container">
<div class="row">
<div>
<textarea name="tweettext" id="tweettext" onKeyUp="textCounter();" onKeyDown="textCounter();" onChange="textCounter();">
</textarea>
</div>
<div id="output" class="black">
</div>
</div>
</div>
Therefore, what am I overlooking in the initial implementation using addEventListener
?