Minimalist Character Counter For jQuery & Vanilla JavaScript

Minimalist Character Counter For jQuery & Vanilla JavaScript
File Size: 5.61 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

This is a basic character counter plugin for input or textarea element, implemented in jQuery or Vanilla JavaScript.

Also provides 2 examples in the zip that demonstrates how to create a character counter in Angular & Vue.js.

How to use it:

1. Create an element to display how many characters were typed in a text field.

<p>Characters: <span class="counter">0</span></p>
<input class="input-demo">
<textarea class="textarea-demo">
</textarea>

2. The JavaScript to enable the character counter.

let getInput = document.getElementsByTagName('textarea'); // or input
const getSpan = document.getElementsByTagName('span');

function calculate() {
  let innerInput = getInput[0].value;
  let calc = innerInput.length;
  getSpan[0].innerText = calc;
  }

getInput[0].addEventListener('input', calculate);

3. To implement the character counter in your jQuery project, copy the following snippets and paste them into the document, after the latest jQuery library.

<script src="/path/to/jquery.js"></script>
let getInput = $('textarea'); // or input
const getspan = $('span');

function calculate() {
  let innerInput = getInput[0].value;
  let calc = innerInput.length;
  getspan.text(calc);
  }

getInput.on('input', calculate);

This awesome jQuery plugin is developed by PeterMorganGH. For more Advanced Usages, please check the demo page or visit the official website.