user3046711
user3046711

Reputation:

I want a text counter to work on my page without using jquery?

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

Answers (3)

Jeremy Thille
Jeremy Thille

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

le_m
le_m

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

Tamas Hegedus
Tamas Hegedus

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

Related Questions