Reputation:
I want a text counter that will instantly count the characters in textarea and display them in textarea_feedback.
Ideally it would count to 160, then when it hits 160 it would go back to 0 and start counting again.
So far i've gotten this, which isn't working
document.addEventListener('load', function() {
document.getElementById('textarea').onkeyup = function () {
document.getElementById('textarea_feedback').innerHTML = "Characters left: " + (500 - this.value.length);
};
})
Upvotes: 0
Views: 54
Reputation: 26400
The first line doesn't work.
Remove document.addEventListener('load', function()
and just put your code at the end of the <body>
.
function updateText () {
feedback.innerHTML = "Characters left: " + (500 - textArea.value.length);
};
var textArea = document.getElementById('textarea'),
feedback = document.getElementById('textarea_feedback');
textArea.onkeyup = function(){ updateText() };
textArea.onpaste = function(){ updateText() };
<textarea id="textarea"></textarea>
<div id="textarea_feedback"></div>
Upvotes: 1
Reputation: 20248
Use the input
event to capture all changes to the input's value by pasting, undoing, autofill etc.:
var input = document.getElementById('textarea'),
feedback = document.getElementById('textarea_feedback');
input.addEventListener('input', event => {
var remaining = 160 - (event.target.value.length % 160);
feedback.textContent = `${remaining} characters remaining`;
});
<textarea id="textarea"></textarea>
<div id="textarea_feedback"></div>
Upvotes: 0
Reputation: 29936
How about this? Using the remainder operator will let you start over from 0. And the load
event is fired on the window
object not on document
.
window.addEventListener("load", function(){
document.getElementById('textarea').onkeyup = function () {
var charsLeft = 160 - this.value.length % 160;
document.getElementById('textarea_feedback').innerHTML = "Characters left: " + charsLeft;
};
});
<textarea id="textarea"></textarea>
<div id="textarea_feedback"></div>
Upvotes: 0