In this example here I used JQuery Simply Countable plugin to created two text boxes, the first one is counting down and accept only 140 characters before its counter will show the red colour. 

And the second one is counting up and calculate the number of words in a given text or while typing.

How the Code works:

When the DOM is ready, JQ will observe whatever inside the two textareas and apply simplyCountable() function.

The simplyCountable() is accepting options.

If the user didn’t pass on any options with the function (like I did in line 2) then the default options will be applied as follows:

options = $.extend({
counter: '#counter',
countType: 'characters',
maxCount: 140,
strictMax: false,
countDirection: 'down',
safeClass: 'safe',
overClass: 'over',
thousandSeparator: ',',
onOverCount: function(){},
onSafeCount: function(){},
onMaxCount: function(){}
}, options);

So, I passed on the following properties as an object to simplyCountable() to control the counters after selecting them by IDs:

Code:

$(document).ready(function () {
  $('#letters_counter').simplyCountable();
  $('#words_counter').simplyCountable({
    counter: '#counter2',
    countType: 'words',
    maxCount: 10,
    countDirection: 'up'
  });
});

HTML:

<div class="counters">
  <div class="row">
    <div class="col-md-6">
      <form>
        <fieldset>
          <legend>Letters Counter</legend>
          <p>You have <span id="counter"></span> characters left.</p>
          <p>
            <textarea id="letters_counter" cols="50" rows="4"></textarea>
          </p>
          <p>
            <input type="reset" value="Reset">
          </p>
        </fieldset>
      </form>
    </div>
    <div class="col-md-6">
      <form>
        <fieldset>
          <legend>Word Counter</legend>
          <p>You have used <span id="counter2"></span> words.</p>
          <p>
            <textarea id="words_counter" cols="50" rows="4"></textarea>
          </p>
          <p>
            <input type="reset" value="Reset">
          </p>
        </fieldset>
      </form>
    </div>
  </div>
</div>

Problems/Mistakes/Bugs:

  • Wrapping up the plugin code with (function($){ ... })(jQuery);
    to avoid the error “Uncaught TypeError: Cannot read property ‘fn’ of undefined” that because we are using an old version of JQuery here.

Implementation/Result:

Letters Counter

You have characters left.

Word Counter

You have used words.