Character Counter for Text Areas with Vanilla JavaScript

Character Counter for Text Areas with Vanilla JavaScript

Introduction

A character counter is a handy UI feature that displays the remaining number of characters a user can input in a text field - if a text field is bounded to a relatively small input size (such as Twitter's limit on 280 characters per tweet). This feature is commonly used alongside text area and/or input field elements to notify a user of the number of used and remaining characters.

In this article, we will learn how to implement a character counter for text areas in JavaScript from scratch.

Probably the most famous example of a character counter is Twitter's character counter. It notifies you when the length of your tweet approaches and exceeds 280 characters, but doesn't prevent you from typing more characters. This feature is widely beloved because it doesn't cut off text when you paste a chunk of text longer than the prescribed length of characters and allows you to appropriately plan how you'll break it down into multiple tweets!

By the end of this article, you will be able to make an input field like this:

Note: All of the code involved in creating the form will be present in the guide. Additionally, the source code and live preview are available on CodePen.

How to Implement a Character Counter in JavaScript

The first thing we need to set up before implementing the character counter is a basic HTML form. It will contain a textarea field and a text representing a character counter. It displays the maximum number of characters and the number of characters left. If the allowed number of characters is exceeded, the text changes color to red:

<form>
    <h3>Write Bio: </h3>
    <textarea name="tweet" id="textbox" class="form-control" rows="10" cols="60"></textarea>
    <span id="char_count">100/100</span>
    <button type="submit">Save</button>
</form>

Declaring Variables

After creating a basic HTML form, the next step is to implement a character counter logic using JavaScript. The first step in creating the JavaScript logic is to define our variables and obtain the DOM components we'll be utilizing later. Specifically the textarea field and the span element displaying the character counter:

let textArea = document.getElementById("textbox");
let characterCounter = document.getElementById("char_count");
const maxNumOfChars = 100;

The textArea will be used to add an event that will activate the logic function. There are numerous events we can use, but the keyup is the best fit for this use case since it will trigger the logic function every time a key is pushed - a character is added or removed from the textarea. The characterCounter is used to display the character counter, and the maxNumOfChars defines the maximum number of characters a user can enter.

Implementing The Logic

The next step would be to create the fundamental logic that allows us to determine the length of the text typed into the textArea, as well as to deduct the length from the maximum number of characters we've chosen. This is what the structure of the logic function could look like:

const countCharacters = () => {
    // Calculate the number of characters entered into the textarea
    // Calculate the number of characters left
    // Display this number in the span tag
};

And here is how the implementation of the mentioned structure looks like:

const countCharacters = () => {
    let numOfEnteredChars = textArea.value.length;
    let counter = maxNumOfChars - numOfEnteredChars;
    characterCounter.textContent = counter + "/100";
};

Note: Please keep in mind that countCharacters() does not handle any style at the moment. For example, we'd like to turn the counter color to red when the maximum number of characters is being approached or exceeded. We'll implement this in a moment, since it's a more subjective type of addition.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Finally, in order for this to work, we must add an eventListener that will trigger/call this method anytime a character is added/removed from the textarea field by using the input event. Alternatively, we can use the keyup or keydown events instead:

textArea.addEventListener("input", countCharacters);

Customizing The Counter Color

We'd like to 'alert' a user when the defined maximum number of characters is surpassed as well as when they're approaching it. This is readily accomplished by using conditional statements where we check if the counter is less than zero or less than, say, 20 if we want to alert them that they're approaching the limit:

if (counter < 0) {
    characterCounter.style.color = "red";
} else if (counter < 20) {
    characterCounter.style.color = "orange";
} else {
    characterCounter.style.color = "black";
}

Here, we've only changed the text based on the number of characters left. There's a lot you can change there. For example, you can disable the textarea if too many characters are typed, truncate the content automatically, and so on.

Conclusion

In this short guide - we've taken a look at how to create a character counter and attach it to a text area in JavaScript, from scratch, with minimal and performant code.

Last Updated: June 15th, 2022
Was this article helpful?

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms