title: A character counter in js?
body: <p>So I am currently programming my very first website. I am using pure javascript. A part of it will be a comments section - which are stored in a SQL- Database on the server. I want comments to have a maximum length. After searching the web I found this solution. Please do note that this solution is far from perfect.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var maxchar = 160;
  var i = document.getElementById("textinput");
  var c = document.getElementById("count");
  c.innerHTML = maxchar;
  
  i.addEventListener("keydown", count);
  
  function count(e) {
    var len = i.value.length;
    if (len &gt;= maxchar) {
      e.preventDefault();
    } else {
      c.innerHTML = maxchar - len - 1;
    }
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
    display: block;
    width: 200px;
    height: 100px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>Remaining characters: &lt;span id="count"&gt;&lt;/span&gt;
  &lt;textarea id="textinput"&gt;
  &lt;/textarea&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I found a lot of similar solutions also using jQuery. Now this solution has two major flaws. First it counts the characters before the new character is entered since the registered event is the keydown event - value.length will always give the old count. Secondly once you hit the maximum amount of characters it will prevent all user input - there is no way to delete characters anymore.</p>
  
  <p>Registering the count to keyup doesn't help either - it can't prevent the input of the keydown event.</p>
  
  <p>What is a better solution than this?</p>