Live word counter from HTML textarea in JavaScript

By informerfrk

Here in this tutorial, I am going to show you how you can build a simple live word counter that will count the word of the text content inside HTML textarea perfectly.


At first, let’s create an HTML textarea field and give it an id:

<textarea id="textcontent" style="width: 455px; height: 200px;"></textarea>

You can see that we give it the id “textcontent”. We have also added some inline CSS to give it a better look.

Show live preview of HTML textarea with JavaScript

Now let’s create a div element where the result will be shown:

<div id="countWord"></div>

We have given it the id “countWord”. After applying the JavaScript code, it will show the number of words inside the text box at the time of writing. It will be a completely live word counter. The value will be change automatically when you write inside the text box.

Simple Animation Example Using jQuery

Now the complete HTML code is given below:

<div style="text-align: center;">
   <textarea id="textcontent" style="width: 455px; height: 200px;"></textarea>
   <div id="countWord"></div>

We have kept all the HTML code inside a div element and added inline CSS to position it center.

The JavaScript:

Now all the functionality will be done by JavaScript that is given below:

function count_word( val ){
    var wom = val.match(/\S+/g);
    return {
        words : wom ? wom.length : 0

var textContent = document.getElementById("textcontent");
var showWordCount   = document.getElementById("countWord");

textContent.addEventListener("input", function(){
  var v = count_word( this.value );
  showWordCount.innerHTML = (
      "<br>Words: "+ v.words
}, false);

The above JavaScript code will add the live word counter functionality. You can see the live word counter at the time of writing anything inside the HTML text box. The result will be shown in the div element “countWord”.

Play/Pause Button For HTML5 Video Using JavaScript

That’s it. All its done. You can see the number of words while you are typing inside the text box. You can also test the code snippets on your browser to see how it works. We have used just a few line of JavaScript code to give a live word counter functionality. I hope you have liked this tutorial and it’s going to be helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *